How to install a Windows Service without Setup?

Asked

Viewed 1,319 times

12

I have a Windows Service project in Visual Studio in C#, however, I need to install this project from lines of code, without use the Installutil of console nor the Setup of Visual Studio.

There’s some way to do it?

1 answer

13

You can use the class ManagedInstallerClass (responsible for dealing with the functionality of Installutil), more specifically, the method InstallHelper:

static void Main(string[] args) {
    if (System.Environment.UserInteractive) {
        if (args.Length > 0) {
            switch (args[0]) {
                case "-install": {
                   ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                   break;
                }
                case "-uninstall": {
                   ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                   break;
                }
            }
        }
    }
    else {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] { new MyService() };
        ServiceBase.Run(ServicesToRun);
    }
}

Source

Example of use:

  • Install: meuProjeto.exe -install
  • Uninstall: meuProjeto.exe -uninstall

Browser other questions tagged

You are not signed in. Login or sign up in order to post.