一些背景知识:基本上我想为私有(private)和公共(public)网络添加一个程序防火墙访问规则。
我以前用这个- "netsh firewall add allowedprogram program= "Path.."name=AppName ENABLE scope=ALL profile=CURRENT"
但现在我想使用 COM 对象稍微自动化该过程。 找到这段 Shiny 的代码 - http://web.archive.org/web/20070707110141/http://www.dot.net.nz/Default.aspx?tabid=42&mid=404&ctl=Details&ItemID=8
在实现我一直尝试使用的类之后- FirewallHelper.Instance.GrantAuthorization(@"Path...","AppName",NET_FW_SCOPE_.NET_FW_SCOPE_ALL,NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY);
我面临的问题是 GrantAuthorization 方法只会为公共(public)或专用网络添加一条规则,而我的旧 netsh 命令会为每个网络添加 2 条规则 - 1 条。
这些命令实际上看起来非常相似,所以我有点困惑。
那么...如何添加两个网络规则?
肖恩
最佳答案
我的回答来自大卫的回答,但更详细。并修复有关设置 Localports 的问题。您需要在设置 Localports 之前设置协议(protocol)。更多详情如下:
首先,您需要导入reference FirewallAPI.dll。它在“C:\Windows\System32\FirewallAPI.dll”中 然后:
using NetFwTypeLib;
并将代码插入您的:
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);
关于c# - 通过 win7 FirewallAPI 向私有(private)和公共(public)网络添加应用程序防火墙规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15409790/