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

时间:2012-10-31 12:52:37

标签: c# windows-services firewall

  

可能重复:
  Programmatically add an application to Windows Firewall

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

1 个答案:

答案 0 :(得分:6)

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

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();
        }
    }
}