将AP加入防火墙例外C# 方法

来源:互联网 发布:网络歌曲 悲伤 一个人 编辑:程序博客网 时间:2024/06/05 17:33

微软有提供firewall的接口:firewallapi.dll

C# 使用添加引用 NetFwTypeLib, C++ 中使用#include "netfw.h"

以下为C#中的实现,
        private void setFirewall()
        {
            Type TfwMgr = Type.GetTypeFromProgID("HNetCfg.FwMgr");
            NetFwTypeLib.INetFwMgr iFwMgr = (INetFwMgr)Activator.CreateInstance(TfwMgr);
            NetFwTypeLib.INetFwPolicy iFwPolicy = iFwMgr.LocalPolicy;
            NetFwTypeLib.INetFwProfile iFwProfile = iFwPolicy.CurrentProfile;
            NetFwTypeLib.INetFwServices iServices = iFwProfile.Services;
            INetFwService service = iServices.Item(NET_FW_SERVICE_TYPE_.NET_FW_SERVICE_REMOTE_DESKTOP);
                  
           String name = service.Name;//获得服务的名称,此处为“远程桌面”
            try
            {
                bool remotedesktop = service.Enabled;//获得和设置enable会引起异常,原因不明. ----> 好像因为我的电脑在公司域内,被域管理员禁止修改远程桌面使用属性,所以无法获得和设置此项,使用自己的笔记本则可以正常访问和设置。
            }
            catch (Exception e)
            {

               // service.Enabled = true;
                int x = 0;
            }

        }
        private void addtoApList()//添加自己的AP到防火墙例外程序中
        {
            Type TfwMgr = Type.GetTypeFromProgID("HNetCfg.FwMgr");
            NetFwTypeLib.INetFwMgr iFwMgr = (INetFwMgr)Activator.CreateInstance(TfwMgr);
            NetFwTypeLib.INetFwPolicy iFwPolicy = iFwMgr.LocalPolicy;
            NetFwTypeLib.INetFwProfile iFwProfile = iFwPolicy.CurrentProfile;
            INetFwAuthorizedApplications apps = iFwProfile.AuthorizedApplications;
         
            Type tapp= Type.GetTypeFromProgID("HNetCfg.FwAuthorizedApplication");//HNetCfg.FwAuthorizedApplication
            INetFwAuthorizedApplication apself = (INetFwAuthorizedApplication)Activator.CreateInstance(tapp);
            apself.ProcessImageFileName = "E:\\RDandRA_Client.exe";
            apself.Name = "123";
            apps.Add(apself);

        }

        //HNetCfg.HNetShare、HNetCfg.NATUPnP、HNetCfg.FwMgr、HNetCfg.FwOpenPort、HNetCfg.FwAuthorizedApplication