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

 

posted @ 2012-07-30 11:39  itbread  阅读(1279)  评论(0编辑  收藏  举报

如果觉得对你有帮助,不妨微信扫描打赏鼓励下