通过c sharp获取防火墙状态和修改和添加防火墙规则
时间: 2024-02-13 10:06:50 浏览: 138
你可以使用C#中的System.Management命名空间中的ManagementObject类来获取防火墙状态和修改和添加防火墙规则。以下是获取防火墙状态的示例代码:
```csharp
using System.Management;
public static bool IsFirewallEnabled()
{
bool isEnabled = false;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM CIM_Service WHERE DisplayName = 'Windows Firewall'");
foreach (ManagementObject obj in searcher.Get())
{
isEnabled = (bool)obj["Started"];
break;
}
return isEnabled;
}
```
以下是添加防火墙规则的示例代码:
```csharp
using System.Management;
public static void AddFirewallRule(string ruleName, string ruleDescription, string applicationPath, bool isEnable = true)
{
ManagementObject classInstance = new ManagementObject("root\\StandardCimv2", "MSFT_NetFirewallRule", null);
//set properties for the new rule
classInstance.SetPropertyValue("Name", ruleName);
classInstance.SetPropertyValue("Description", ruleDescription);
classInstance.SetPropertyValue("ApplicationPath", applicationPath);
classInstance.SetPropertyValue("Enabled", isEnable);
classInstance.SetPropertyValue("Direction", 1); // 1 = Inbound, 2 = Outbound
classInstance.SetPropertyValue("Profile", 0x7fffffff); // All profiles
//invoke the Create method to create the new rule
ManagementBaseObject inParams = classInstance.GetMethodParameters("Create");
ManagementBaseObject outParams = classInstance.InvokeMethod("Create", inParams, null);
}
```
同理,你也可以使用相似的代码来修改和删除防火墙规则。
阅读全文