一、强制开启Windows系统防火墙
在C#中强制开启Windows系统防火墙可以通过调用Windows防火墙的COM接口或执行命令行命令实现。以下是两种方法的示例代码:
方法一:通过COM接口操作防火墙(推荐)
using System;
using System.Runtime.InteropServices;
public class FirewallHelper
{
    // 定义防火墙策略的COM接口
    [ComImport]
    [Guid("E2B3C97F-6AE1-41AC-817A-F6F92166D7DD")]
    [TypeLibType(4160)]
    public interface INetFwPolicy2
    {
        [DispId(1)]
        int CurrentProfileTypes { get; }
        [DispId(2)]
        bool FirewallEnabled([In] int profileType);
        [DispId(3)]
        void set_FirewallEnabled([In] int profileType, [In] bool enabled);
    }
    // 定义配置文件类型
    public enum NET_FW_PROFILE_TYPE2
    {
        NET_FW_PROFILE2_DOMAIN = 0x1,
        NET_FW_PROFILE2_PRIVATE = 0x2,
        NET_FW_PROFILE2_PUBLIC = 0x4,
        NET_FW_PROFILE2_ALL = 0x7
    }
    public static void EnableFirewall()
    {
        try
        {
            // 获取防火墙策略实例
            Type type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(type);
            // 启用所有配置文件(域、私有、公共)
            firewallPolicy.set_FirewallEnabled(
                (int)(NET_FW_PROFILE_TYPE2.NET_FW_PROFILE2_ALL),
                true
            );
            Console.WriteLine("防火墙已成功启用!");
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("需要管理员权限!请以管理员身份运行程序。");
        }
        catch (COMException ex)
        {
            Console.WriteLine($"操作失败: {ex.Message}");
        }
    }
}
方法二:通过命令行执行netsh命令
using System;
using System.Diagnostics;
public class FirewallHelper
{
    public static void EnableFirewall()
    {
        try
        {
            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = "netsh",
                Arguments = "advfirewall set allprofiles state on",
                WindowStyle = ProcessWindowStyle.Hidden,
                Verb = "runas", // 请求管理员权限
                UseShellExecute = true
            };
            Process.Start(psi).WaitForExit();
            Console.WriteLine("防火墙已成功启用!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"操作失败: {ex.Message}");
        }
    }
}
使用说明
- 以管理员权限运行程序: 
- 在Visual Studio中,右键项目 → 添加 → 新建项 → 应用程序清单文件。 
- 找到<requestedExecutionLevel>节点,修改为: 
- <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> 
 
- 调用方法: 
static void Main(string[] args)
{
    FirewallHelper.EnableFirewall();
    Console.ReadKey();
}
注意事项
- 两种方法均需管理员权限,否则会抛出异常。 
- COM接口方法更直接,但需要确保系统版本支持(Vista及以上)。 
- 命令行方法兼容性更好,但依赖netsh工具。 
- 若防火墙服务被禁用,需先启用服务(可通过sc config mpssvc start=auto设置)。 
// 通过命令行启用服务
Process.Start("sc", "config MpsSvc start=auto").WaitForExit();
Process.Start("net", "start MpsSvc").WaitForExit();
建议优先使用COM接口方法,因其能提供更精准的控制(如单独配置不同网络类型)。若遇到权限问题,请确保程序以管理员身份运行。
二、强制关闭Windows系统防火墙
以下是使用C#强制关闭Windows系统防火墙的两种方法示例代码,与开启操作类似但参数相反:
方法一:通过COM接口操作防火墙(精准控制)
using System;
using System.Runtime.InteropServices;
public class FirewallHelper
{
    // 定义防火墙策略的COM接口
    [ComImport]
    [Guid("E2B3C97F-6AE1-41AC-817A-F6F92166D7DD")]
    [TypeLibType(4160)]
    public interface INetFwPolicy2
    {
        [DispId(1)]
        int CurrentProfileTypes { get; }
        [DispId(2)]
        bool FirewallEnabled([In] int profileType);
        [DispId(3)]
        void set_FirewallEnabled([In] int profileType, [In] bool enabled);
    }
    // 定义配置文件类型
    public enum NET_FW_PROFILE_TYPE2
    {
        NET_FW_PROFILE2_DOMAIN = 0x1,
        NET_FW_PROFILE2_PRIVATE = 0x2,
        NET_FW_PROFILE2_PUBLIC = 0x4,
        NET_FW_PROFILE2_ALL = 0x7
    }
    public static void DisableFirewall()
    {
        try
        {
            // 获取防火墙策略实例
            Type type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
            INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(type);
            // 关闭所有配置文件(域、私有、公共)
            firewallPolicy.set_FirewallEnabled(
                (int)NET_FW_PROFILE_TYPE2.NET_FW_PROFILE2_ALL,
                false  // 关键修改点:false表示关闭
            );
            Console.WriteLine("防火墙已成功关闭!");
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("需要管理员权限!请以管理员身份运行程序。");
        }
        catch (COMException ex)
        {
            Console.WriteLine($"操作失败: {ex.Message}");
        }
    }
}
方法二:通过命令行执行netsh命令(快速实现)
using System;
using System.Diagnostics;
public class FirewallHelper
{
    public static void DisableFirewall()
    {
        try
        {
            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = "netsh",
                Arguments = "advfirewall set allprofiles state off",  // 关键修改点:on → off
                WindowStyle = ProcessWindowStyle.Hidden,
                Verb = "runas", // 请求管理员权限
                UseShellExecute = true
            };
            Process.Start(psi).WaitForExit();
            Console.WriteLine("防火墙已成功关闭!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"操作失败: {ex.Message}");
        }
    }
}
调用方式(与开启操作一致)
static void Main(string[] args)
{
    FirewallHelper.DisableFirewall();
    Console.ReadKey();
}
关键注意事项
- 管理员权限 - 必须通过清单文件 (app.manifest) 要求管理员权限: 
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
- 配置文件选择 
// 仅关闭公共网络防火墙
firewallPolicy.set_FirewallEnabled(
    (int)NET_FW_PROFILE_TYPE2.NET_FW_PROFILE2_PUBLIC,
    false
);
- 防火墙服务状态 - 如果防火墙服务 (MpsSvc) 被禁用,需先启用服务: 
// 通过命令行启用服务
Process.Start("sc", "config MpsSvc start=auto").WaitForExit();
Process.Start("net", "start MpsSvc").WaitForExit();
- 系统兼容性 
两种方法对比:
| 方法 | 优点 | 缺点 | 
|---|
| COM接口 | 精准控制配置文件,无需外部进程 | 依赖系统版本 | 
| 命令行 | 兼容性更好,代码简单 | 依赖 netsh工具 | 
根据需求选择方法:需要精细控制时用COM接口,追求兼容性则用命令行。
该文章在 2025/3/4 11:54:28 编辑过