[英]How to enable/disable Firewall?
INetFwPolicy2接口允许应用程序或服务访问防火墙策略。
我正在使用 Visual Studio 2017。
问题与此有关https://stackoverflow.com/a/33700472/2451446
代码几乎没有什么不同,我在禁用防火墙时遇到了问题。
禁用防火墙之前的逻辑是可以的。
public Task<StatusCodeResult> ResetFirewallStatus()
{
Type netFwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
dynamic mgr = Activator.CreateInstance(netFwPolicy2Type);
var fwCurrentProfileTypes = mgr.CurrentProfileTypes;
// Get current status
bool firewallEnabled = mgr.FirewallEnabled(fwCurrentProfileTypes); // return true
// Disables Firewall
mgr.FirewallEnabled(false); //breaks here !!!!
return Task.FromResult<StatusCodeResult>(Ok());
}
错误信息是:
System.ArgumentException: '值不在预期范围内。'
我尝试使用set_FirewallEnabled(fwCurrentProfileTypes,false);
还有put_FirewallEnabled(fwCurrentProfileTypes,false)
在这种情况下,错误是:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“System.__ComObject”不包含“set_FirewallEnabled”的定义(“put_FirewallEnabled”)
编辑
我的解决方案:
const int domainProfile = 1;
const int privateProfile = 2;
const int publicProfile = 4;
public bool EnableDisableFirewall(bool enableFirewall)
{
dynamic mgr = getFwPolicy2();
mgr.FirewallEnabled[domainProfile] = enableFirewall;
mgr.FirewallEnabled[privateProfile] = enableFirewall;
mgr.FirewallEnabled[publicProfile] = enableFirewall;
return enableFirewall;
}
public bool IsFirewallOn()
{
dynamic mgr = getFwPolicy2();
// Get current status
var isDomainProfileEnabled = mgr.FirewallEnabled(domainProfile);
var isPrivateProfileEnabled = mgr.FirewallEnabled(privateProfile);
var isPublicProfileEnabled = mgr.FirewallEnabled(publicProfile);
return isDomainProfileEnabled && isPrivateProfileEnabled && isPublicProfileEnabled;
}
private object getFwPolicy2()
{
Type netFwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
dynamic mgr = Activator.CreateInstance(netFwPolicy2Type);
return mgr;
}
你有两个问题,后期编写这段代码并不能完全帮助做到这一点。 添加对 c:\\windows\\system32\\firewallapi.dll 的引用,以便您可以直接使用 INetFwPolicy2 接口帮助您正确使用。 您正在解决的一个怪癖是 FirewallEnabled 属性是一个索引属性。 C# 语言中没有等效项。 Anyhoo,后期绑定需要:
bool firewallEnabled = mgr.FirewallEnabled(fwCurrentProfileTypes);
MSDN 文档对此特别警告,您不能使用 CurrentProfileTypes 返回的值。 它需要指定一个特定的配置文件。 我建议你使用:
int profile = 2; // 1=domain, 2=private, 4=public
bool firewallEnabled = mgr.FirewallEnabled[profile];
请注意 [尖括号] 的使用,允许在 COM 实现的属性的特定情况下索引属性。
mgr.FirewallEnabled(false); //这里断了!!!!
您必须选择要禁用的特定配置文件。 正确的语法如下所示:
mgr.FirewallEnabled[profile] = false;
请注意,当您的程序以管理员权限运行时,您只能修改防火墙。 如果您还没有这样做,请添加所需的清单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.