示例
using System; using System.Net; using System.Net.NetworkInformation; using System.Text; //64位系统: 需要引入C:\Windows\SysWOW64\FirewallAPI.dll //32位系统: 需要引入C:\Windows\System32\FirewallAPI.dll using NetFwTypeLib; namespace ConsoleApp6 { class Program { static void Main(string[] args) { FirewallOperateByObject(false, false, false); Console.WriteLine("FirewallEnabled={0}", FirewallEnabled); Console.ReadLine(); } // 判断Windows防火墙有没开启 (仅能判断公用网络位置) private static bool FirewallEnabled { get { INetFwMgr netFwMgr = GetFirewallManager(); return netFwMgr.LocalPolicy.CurrentProfile.FirewallEnabled; } } private static INetFwMgr GetFirewallManager() { const string CLSID_FIREWALL_MANAGER = "{304CE942-6E39-40D8-943A-B913C40C9CD4}"; Type objType = Type.GetTypeFromCLSID(new Guid(CLSID_FIREWALL_MANAGER)); return Activator.CreateInstance(objType) as INetFwMgr; } /// <summary> /// 转载自 https://www.cnblogs.com/pilgrim/p/11135485.html /// 通过对象防火墙操作 /// </summary> /// <param name="isOpenDomain">域网络防火墙(禁用:false;启用(默认):true)</param> /// <param name="isOpenPublicState">公共网络防火墙(禁用:false;启用(默认):true)</param> /// <param name="isOpenStandard">专用网络防火墙(禁用: false;启用(默认):true)</param> /// <returns></returns> public static bool FirewallOperateByObject(bool isOpenDomain = true, bool isOpenPublicState = true, bool isOpenStandard = true) { try { INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); // 启用<高级安全Windows防火墙> - 专有配置文件的防火墙 firewallPolicy.set_FirewallEnabled(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE, isOpenStandard); // 启用<高级安全Windows防火墙> - 公用配置文件的防火墙 firewallPolicy.set_FirewallEnabled(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC, isOpenPublicState); // 启用<高级安全Windows防火墙> - 域配置文件的防火墙 firewallPolicy.set_FirewallEnabled(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN, isOpenDomain); } catch (Exception e) { string error = $"防火墙修改出错:{e.Message}"; throw new Exception(error); } return true; } } }