以编程方式管理 Windows 防火墙

Ice*_*ind 10 c# windows-firewall

我正在尝试以编程方式创建出站 Windows 防火墙规则。此外,我想以编程方式启用和禁用此规则。我怎样才能在 C# 中做到这一点?手动,我可以通过进入控制面板,单击 Windows 防火墙,然后单击高级设置来执行此操作。

nee*_*ing 7

最好使用 Windows 库 C:\windows\system32\FirewallAPI.dll。此 DLL 自 Windows 7 起可用。如果您将其添加到项目引用中,Visual Studio 将自动为此 COM 库添加包装器,或者您可以使用 tlbimp.exe 手动创建包装器。

using NetFwTypeLib;

INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description = "Your rule description";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; // inbound
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.RemoteAddresses = "1.2.3.0/24"; // add more blocks comma separated
firewallRule.Name = "You rule name";
firewallPolicy.Rules.Add(firewallRule);
Run Code Online (Sandbox Code Playgroud)

VS IntelliSense 应该为您提供有关该库的足够详细信息。


liv*_*ve2 5

您可以使用此 nuget 包WindowsFirewallHelper

PM> Install-Package WindowsFirewallHelper
Run Code Online (Sandbox Code Playgroud)

示例代码为应用程序添加新的出站规则

PM> Install-Package WindowsFirewallHelper
Run Code Online (Sandbox Code Playgroud)


Ben*_*rth 4

您可以将 netsh advfirewall 命令语法包装到一个小型库中,以允许您按需启用/禁用设置。如果失败,请参阅http://msdn.microsoft.com/en-us/library/windows/desktop/ff956124(v=vs.85).aspx了解具有高级安全 API 的 Windows 防火墙。