C# 如何禁用Windows防火墙?

C# 如何禁用Windows防火墙?,c#,.net,windows,firewall,C#,.net,Windows,Firewall,Windows 7、8.1 当我尝试禁用Windows防火墙时出现异常。我试着用管理员权限来做。但对于Windows防火墙启用,我没有同样的问题 如何禁用Windows防火墙?您似乎正在使用Windows XP SP2 COM API,众所周知,Windows Vista/7和更新版本上存在问题 建议您使用更新的API: (我还没有测试过这个) 在Main.cs yourclass.Firewall()什么是“HNetCfg.FwMg”只是一个猜测,但当我看到“net_sandbox.exe”时

Windows 7、8.1

当我尝试禁用Windows防火墙时出现异常。我试着用管理员权限来做。但对于Windows防火墙启用,我没有同样的问题


如何禁用Windows防火墙?

您似乎正在使用Windows XP SP2 COM API,众所周知,Windows Vista/7和更新版本上存在问题

建议您使用更新的API:

我还没有测试过这个

在Main.cs


yourclass.Firewall()

什么是“HNetCfg.FwMg”只是一个猜测,但当我看到“net_sandbox.exe”时,我认为您不能做任何事情来降低安全配置。我不会有同样的限制。@roryap,@JohnPrideaux,我不明白你的意思。这是一个用于测试的简单控制台项目。如果我没记错的话,.NET使用信任模型运行。如果您不是在完全信任的情况下运行,那么您将处于一个“沙箱”中,并且对于网络和文件系统的安全性,您所能做的将是有限的。
Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);

// Get the Windows Firewall status
bool firewallEnabled = mgr.LocalPolicy.CurrentProfile.FirewallEnabled;

// it works fine...
String frw_status = "Windows Firewall is " + (firewallEnabled ?
    "enabled" : "disabled");

// Enable or disable firewall.

// I get the exception here when I try to disable Windows Firewall.
// I have not problem when I try to enable Windows Firewall (it works fine).
//
// Exception message:
//   An unhandled exception of type 'System.NotImplementedException' 
//   occurred in net_sandbox.exe
//   Additional information: Method or operation is not emplemented yet..
mgr.LocalPolicy.CurrentProfile.FirewallEnabled = false;
Type netFwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
INetFwPolicy2 mgr = (INetFwPolicy2)Activator.CreateInstance(netFwPolicy2Type);

// Gets the current firewall profile (domain, public, private, etc.)
NET_FW_PROFILE_TYPE2_ fwCurrentProfileTypes = (NET_FW_PROFILE_TYPE2_)mgr.CurrentProfileTypes;

// Get current status
bool firewallEnabled = mgr.get_FirewallEnabled(fwCurrentProfileTypes);
string frw_status = "Windows Firewall is " + (firewallEnabled ?
"enabled" : "disabled");

// Disables Firewall
mgr.set_FirewallEnabled(fwCurrentProfileTypes, false);
private const string CLSID_FIREWALL_MANAGER =
  "{304CE942-6E39-40D8-943A-B913C40C9CD4}";

private static NetFwTypeLib.INetFwMgr GetFirewallManager()
{
    Type objectType = Type.GetTypeFromCLSID(
          new Guid(CLSID_FIREWALL_MANAGER));
    return Activator.CreateInstance(objectType)
          as NetFwTypeLib.INetFwMgr;
}

public static void Firewall()
{
    INetFwMgr manager = GetFirewallManager();
    bool isFirewallEnabled = manager.LocalPolicy.CurrentProfile.FirewallEnabled;
    manager.LocalPolicy.CurrentProfile.FirewallEnabled = false;
}