必须添加 NetFwTypeLib
,在 引用
> 添加引用
> COM
/// <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);
}
转载请保留原文链接: https://zodream.cn/blog/id/151.html