3

Possible Duplicate:
Programmatically add an application to Windows Firewall

in my solution i have an windows service project and installer to install this service How i can add this service to Windows Firewall During Installation.

Community
  • 1
  • 1
Tarek Saied
  • 6,482
  • 20
  • 67
  • 111
  • Depending on the deployment project, but [here's a solution for wix](http://wix.sourceforge.net/manual-wix3/firewall_xsd_firewallexception.htm) – Patrick Oct 31 '12 at 13:20
  • You should really expand with more details of your problem.. What have you tried? What type of "installer" are you using? – Patrick Oct 31 '12 at 13:21
  • 1
    I don't think this exact duplicate, other issue is about a ClickOnce installer. – weston Oct 31 '12 at 23:55

1 Answers1

8

Assuming we're using a Visual Studio Installer->Setup Project - You need an installer class like this inside an assembly that's being installed, and then make sure you add a custom action for the "Primary output" in the install phase.

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();
        }
    }
}
weston
  • 54,145
  • 21
  • 145
  • 203
  • thanks weston but What do you mean "YourExe.exe" , you mean full path + exe file name – Tarek Saied Oct 31 '12 at 14:16
  • @tito11 - Sorry, yes you do need the path, please see modifications to code. – weston Oct 31 '12 at 15:20
  • Today you should use: `netsh advfirewall firewall add rule name="My Application" dir=in action=allow program="C:\MyApp\MyApp.exe" enable=yes` see https://go.microsoft.com/fwlink/?linkid=121488 – Wollmich Jul 17 '20 at 11:20