c# 添加防火墙例外端口

Fork Me On Github
zodream 编程技术 C# 2020年05月

必须添加 NetFwTypeLib ,在 引用 > 添加引用 > COM

ts
                                    
/// <summary>
/// 添加防火墙例外端口
/// </summary>
/// <param name="name">名称</param>
/// <param name="port">端口</param>
/// <param name="protocol">协议(TCP、UDP)</param>
public static void NetFwAddPorts(string name, int port, string protocol)
{
    INetFwMgr netFwMgr = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));

    INetFwOpenPort objPort = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwOpenPort"));

    objPort.Name = name;
    objPort.Port = port;
    if (protocol.ToUpper() == "TCP")
    {
        objPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
    }
    else
    {
        objPort.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;
    }
    objPort.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
    objPort.Enabled = true;

    bool exist = false;
    foreach (INetFwOpenPort mPort in netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts)
    {
        if (objPort == mPort)
        {
            exist = true;
            break;
        }
    }
    if (!exist) netFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(objPort);
}
123456789101112131415161718192021222324252627282930313233343536
点击查看全文
0 300 0