A little background: Basicaly I\'d like to add a program firewall access rule to both private and public networks.
I used to use this- \"netsh firewall add allowedpr
My answer is from David's answer but more detail. And fix problem about setting Localports. You need to setting Protocol before setting Localports. More detail is bellow:
the first, you need to import reference FirewallAPI.dll. It's in "C:\Windows\System32\FirewallAPI.dll" then:
using NetFwTypeLib;
and insert code into your:
Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
var currentProfiles = fwPolicy2.CurrentProfileTypes;
// Let's create a new rule
INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
inboundRule.Enabled = true;
//Allow through firewall
inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
//Using protocol TCP
inboundRule.Protocol = 6; // TCP
//Port 81
inboundRule.LocalPorts = "81";
//Name of rule
inboundRule.Name = "MyRule";
// ...//
inboundRule.Profiles = currentProfiles;
// Now add the rule
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(inboundRule);