Create a firewall rule to open a port for each application programmatically in C #

I need to open a specific port for my application.

I tried using the rule INetFwAuthorizedApplicationfor each application for all ports.

fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app)

Alternatively, open one port for all applications using INetFwOpenPort.

firewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port)

Is there a way to programmatically open only one port for each application programmatically? I can do this manually through the firewall settings.

+5
source share
1 answer

#. , .

fooobar.com/questions/167218/...

, :

using NetFwTypeLib; // Located in FirewallAPI.dll
...
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
    Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description = "Used to block all internet access.";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = "Block Internet";

INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
    Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);
+5

All Articles