How to install a windows service programmatically

2019-01-03 00:54发布

I have 3 projects in my VS solution. One of them is a Web app, the second one is a Windows Service and the last one a Setup project for my Web app.

What I want is by the end of the installation of the web app in my setup project, within my custom action to try and install my windows service given that I have the location of the assembly by then.

8条回答
Deceive 欺骗
2楼-- · 2019-01-03 01:49

Please have a look at this article.


Sometimes you may want to install a Windows Service programmatically, but the target machine does not have InstallUtil.exe.

Add a reference to System.Configuration.Install

Use the code below.

Note that the exeFileName is the InstallerClass .exe and not the ServiceClass .exe.

public static void InstallService(string exeFilename)
{
    string[] commandLineOptions = new string[1] { "/LogFile=install.log" };

    System.Configuration.Install.AssemblyInstaller installer = new System.Configuration.Install.AssemblyInstaller(exeFilename, commandLineOptions);

    installer.UseNewContext = true;    
    installer.Install(null);    
    installer.Commit(null);

}

To uninstall:

public static void UninstallService(string exeFilename)
{
    string[] commandLineOptions = new string[1] { "/LogFile=uninstall.log" };

    System.Configuration.Install.AssemblyInstaller installer = new System.Configuration.Install.AssemblyInstaller(exeFilename, commandLineOptions);

    installer.UseNewContext = true;    
    installer.Uninstall(null);

}
查看更多
We Are One
3楼-- · 2019-01-03 01:51

By using the Topshelf project you can install by calling your executable:

MyService.exe install

Topshelf also takes care of other Windows Service plumbing.

查看更多
登录 后发表回答