請參閱我的answer到您以前的question。
看一看下列行:
private static int Main (string [] args)
{
var application = new NetFwAuthorizedApplication()
{
Name = "MyService",
Enabled = true,
RemoteAddresses = "*",
Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL,
IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY,
ProcessImageFileName = "ServiceAssemblyName.dll",
};
return (FirewallUtilities.AddApplication(application, out exception) ? 0 : -1);
}
的NET_FW_SCOPE_枚舉具有以下值:
- NET_FW_SCOPE_ALL = 0,
- NET_FW_SCOPE_LOCAL_SUBNET = 1,
- NET_FW_SCOPE_CUSTOM = 2 ,
- NET_FW_SCOPE_MAX = 3,
您可以進一步限制規則的端口,協議以及遠程地址。
UPDATE:
這裏是缺少ReleaseComObject
功能。放置任何名稱空間並刪除對ComUtilities
的引用。
public static void ReleaseComObject (object o)
{
try
{
if (o != null)
{
if (Marshal.IsComObject(o))
{
Marshal.ReleaseComObject(o);
}
}
}
finally
{
o = null;
}
}
這裏是NetFwAuthorizedApplication
類:
命名空間MySolution.Configurator.Firewall { 使用系統;使用System.Linq的 ;使用NetFwTypeLib的 ;
public sealed class NetFwAuthorizedApplication:
INetFwAuthorizedApplication
{
public string Name { get; set; }
public bool Enabled { get; set; }
public NET_FW_SCOPE_ Scope { get; set; }
public string RemoteAddresses { get; set; }
public string ProcessImageFileName { get; set; }
public NET_FW_IP_VERSION_ IpVersion { get; set; }
public NetFwAuthorizedApplication()
{
this.Name = "";
this.Enabled = false;
this.RemoteAddresses = "";
this.ProcessImageFileName = "";
this.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
this.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;
}
public NetFwAuthorizedApplication (string name, bool enabled, string remoteAddresses, NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion, string processImageFileName)
{
this.Name = name;
this.Scope = scope;
this.Enabled = enabled;
this.IpVersion = ipVersion;
this.RemoteAddresses = remoteAddresses;
this.ProcessImageFileName = processImageFileName;
}
public static NetFwAuthorizedApplication FromINetFwAuthorizedApplication (INetFwAuthorizedApplication application)
{
return (new NetFwAuthorizedApplication(application.Name, application.Enabled, application.RemoteAddresses, application.Scope, application.IpVersion, application.ProcessImageFileName));
}
}
}
感謝,我想NET_FW_SCOPE_LOCAL_SUBNET是 '私人' 的等價物。 – spiderplant0
多數民衆贊成在奇怪的,我添加它(請參閱添加的行)'port3.Scope = NetFwTypeLib.NET_FW_SCOPE_.NET_FW_SCOPE_LOCAL_SUBNET;'但似乎沒有做任何事情。也嘗試過'NET_FW_SCOPE_ALL'。 – spiderplant0
好像你在操縱全球開放的端口集合。我不確定這是否會允許訪問特定的應用程序,如果您的Windows防火牆設置配置了常見的默認值。查看該答案中的AddApplication方法。它增加了授權的應用程序集合。順便說一下,您可以按原樣使用這兩個類。只需將'Main'方法內容粘貼到您的控制檯應用程序中,您就可以輕鬆前往。 –