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.
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.
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(
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
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 this post was useful to you, follow me on Twitter, Github, Linkedin, or like my Facebook page to stay updated.Follow me on social media and stay updated