创建防火墙规则以c#编程方式打开每个应用程序的端口

Mar*_*rek 5 c# api port firewall windows-firewall

我需要为我的应用程序打开特定端口.

我已尝试INetFwAuthorizedApplication为所有端口使用每个应用程序的规则.

fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app)
Run Code Online (Sandbox Code Playgroud)

或者,为所有应用程序打开一个端口INetFwOpenPort.

firewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port)
Run Code Online (Sandbox Code Playgroud)

有没有办法以编程方式以编程方式为每个应用程序打开单个端口?我可以通过防火墙设置手动完成.

Ing*_*goB 7

您也可以只使用 PowerShell。

using System.Management.Automation;
...
private void OpenPort(int port)
{
    var powershell = PowerShell.Create();
    var psCommand = $"New-NetFirewallRule -DisplayName \"<rule description>\" -Direction Inbound -LocalPort {port} -Protocol TCP -Action Allow";
    powershell.Commands.AddScript(psCommand);
    powershell.Invoke();
}
Run Code Online (Sandbox Code Playgroud)


Col*_*ard 5

关于使用C#中创建防火墙规则的说明来回答阻塞连接的问题.你应该能够适应我想象的任何防火墙规则.

/sf/answers/87011851/

以下代码创建一个防火墙规则,阻止所有网络适配器上的任何传出连接:

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);
Run Code Online (Sandbox Code Playgroud)