以编程方式将Windows服务添加到Windows防火墙(安装期间)

可能重复:
以编程方式将应用程序添加到Windows防火墙

在我的解决方案中,我有一个Windows服务项目和安装程序来安装此服务如何在安装过程中将此服务添加到Windows防火墙。

假设我们正在使用Visual Studio Installer->Setup ProjectVisual Studio Installer->Setup Project – 您需要在正在安装的程序集中安装这样的安装程序类,然后确保在安装阶段为“主输出”添加自定义操作。

 using System.Collections; using System.ComponentModel; using System.Configuration.Install; using System.IO; using System.Diagnostics; namespace YourNamespace { [RunInstaller(true)] public class AddFirewallExceptionInstaller : Installer { protected override void OnAfterInstall(IDictionary savedState) { base.OnAfterInstall(savedState); var path = Path.GetDirectoryName(Context.Parameters["assemblypath"]); OpenFirewallForProgram(Path.Combine(path, "YourExe.exe"), "Your program name for display"); } private static void OpenFirewallForProgram(string exeFileName, string displayName) { var proc = Process.Start( new ProcessStartInfo { FileName = "netsh", Arguments = string.Format( "firewall add allowedprogram program=\"{0}\" name=\"{1}\" profile=\"ALL\"", exeFileName, displayName), WindowStyle = ProcessWindowStyle.Hidden }); proc.WaitForExit(); } } }