Hey Friends, today I’ll make a short blog post brief and straight to the point. Window’s firewall is basically a network security system which makes sure incoming and outgoing traffic on your computer is safe. As software developers we might face situations were by, accessing the windows firewall is required by our software. Most often this is done manually. But it can also be done using good old code. This blog post is just about how to allow your app through the firewall with C# code.
How Allow Your App through the firewall with C#
Recently, I’ve faced a situation were I had to allow an app through Windows Firewall with C# (Both the private and public profile of the firewall). At first, the app was added manually after installation, but I automated that process with C#. After a few Google searches, I came quickly accross several solutions. Although some were working, they only allowed my app through the “Public profile”. Which is not enough. After researching a bit deeper, I came accross a solution to this. This blog post is about accomplishing the following.
- Adding your app to the public and private profiles of the Windows Firewall
- Removing your app from the firewall when needed.
Adding to the Firewall
First you need to reference external libraries provided by Microsoft to access your firewall. These are: hnetcfg.dll and FirewallAPI.dll These are not on nuget, they are found your PC at the following locations. “C:\\Windows\System32\“. These libraries contain helpers to allow you to manipulate firewall rules. You should note that, the app should be run as administrator to function properly.
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FWRule")); INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); firewallRule.ApplicationName = "//App Executable Path"; firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; firewallRule.Description = "sample rule mera"; firewallRule.Enabled = true; firewallRule.InterfaceTypes = "All"; firewallRule.Name = $"// App Name";
To add your app’s rule to your firewall profile, it is very easy.
To remove your app, is just as simple.
firewallPolicy.Rules.Remove($"// App Name");
With this, you will be able to access your fire wall and configure your fire wall to allow your application to the private and public profile. You might also be interested by this blog post about detecting global mouse hooks in C#.If you liked this post, or it was useful to you, please 👍 like it, share it on twitter, facebook or other social media… in case you want to get updated on any new useful post, follow me onTwitter, Github and like my page onFacebook. And every other social media by clicking on the buttons at the end of this post.Follow me on social media and stay updated