简体   繁体   中英

How can I disable Windows Firewall?

Windows 7, 8.1

I get an exception when I try to disable Windows Firewall. I try to do it with admin rights. But I haven't the same problem for Windows Firewall enabling .

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;

How can I disable Windows Firewall?

It seems you're using Windows XP SP2 COM API, which is known to have issues on Windows Vista/7 and newer versions.

It's recommended that you use the newer API:

( I have not tested this )

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;
}

And in Main.cs

yourclass.Firewall();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM