C# 防火墙操作之特定程序

  将特定程序加入防火墙组,与将特定端口加入防火墙流程类似。详情见“C# 防火墙操作之特定端口”。其主要代码为:

/// <summary>
/// 允许应用程序通过防火墙
/// </summary>
/// <param name="appPath">应用程序的绝对路径</param>
/// <exception cref="FileNotFoundException">未找到程序文件</exception>
public static void AllowAppUseFirewall(string appPath)
{
    if(System.IO.File.Exists(appPath)==false)
    {
        throw new System.IO.FileNotFoundException("未找到程序文件");
    }
    //创建firewall管理类的实例: Type的GetTypeFromProgID是通过注册表信息项目创建实例类型
    INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
    //以程序名为规则名创建规则,以便查询
    string name = System.IO.Path.GetFileNameWithoutExtension(appPath);

    NET_FW_PROFILE_TYPE_ currentProfileType = netFwMgr.CurrentProfileType;
    //查找防火墙规则中是否已有同名规则存在
    foreach (INetFwAuthorizedApplication item in netFwMgr.LocalPolicy.GetProfileByType(currentProfileType).AuthorizedApplications)
    {
        if (item.Name == name)
        {
            return;
        }
    }

    //创建一个认证程序类的实例
    INetFwAuthorizedApplication app = (INetFwAuthorizedApplication)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication"));
    
    //在例外列表里,程序显示的名称
    app.Name = name;

    //程序的绝对路径,这里使用程序本身
    app.ProcessImageFileName = appPath;

    //端口的范围,针对哪类或哪个IP地址
    //objPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
    //此处可以指定IP地址版本信息
    //objPort.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_V4;
    //是否启用该规则
    app.Enabled = true;

    //加入到防火墙的管理策略
    netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app);
}

/// <summary>
/// 移除应用程序通过防火墙
/// </summary>
/// <param name="appPath">应用程序的绝对路径</param> public static void RemoveAppUseFirewall(string appPath) { INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr")); //参数为程序的绝对路径 netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(appPath); }
原文地址:https://www.cnblogs.com/pilgrim/p/11173111.html