C# 操作系统防火墙(续集)
之前写的一篇C#操作系统防火墙博客,经网友反馈,操作添加程序例外时会出现异常,今天特又测试了一片,确实出现了异常,现在已经将NetFwAddApps(string name, string executablePath)方法修改过来了,经过测试已经可用,代码如下:
-
/// <summary>/// 将应用程序添加到防火墙例外/// </summary>/// <param name="name">应用程序名称</param>/// <param name="executablePath">应用程序可执行文件全路径</param>public static void NetFwAddApps(string name, string executablePath) {
Type TfwMgr = Type.GetTypeFromProgID("HNetCfg.FwMgr");//创建firewall管理类的实例INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(TfwMgr);
Type tapp = Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication");INetFwAuthorizedApplication app = (INetFwAuthorizedApplication)Activator.CreateInstance(tapp);
//在例外列表里,程序显示的名称app.Name = name;
//程序的路径及文件名app.ProcessImageFileName = executablePath;
//是否启用该规则app.Enabled = true;//加入到防火墙的管理策略netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app);
bool exist = false;
//加入到防火墙的管理策略foreach(INetFwAuthorizedApplication mApp in netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)
{if(app == mApp){exist = true;break;}
}
if(!exist){netFwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app);
}
}

浙公网安备 33010602011771号