How to Install Windows Service Programmatically


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

To install a Windows Service programmatically, you can build an application to install that Windows Service.

  • Add a reference to System.Configuration.Install
  • Use this code:
public static void InstallService(string ExeFilename)
{
    System.Configuration.Install.AssemblyInstaller Installer = new System.Configuration.Install.AssemblyInstaller(ExeFilename);
    Installer.UseNewContext = true;
    Installer.Install(null);
    Installer.Commit(null);
}

To uninstall:

public static void UninstallService(string ExeFilename)
{
    System.Configuration.Install.AssemblyInstaller Installer = new System.Configuration.Install.AssemblyInstaller(ExeFilename);
    Installer.UseNewContext = true;
    Installer.Uninstall(null);
}

Comments (10)

  1. gOODiDEA.NET says:

    .NET ASP.NET MVC Beta Source Code Release – Partial Output Caching in ASP.NET MVC – Partial Requests

  2. When you created a Windows Service, you usually add a Service Installer to allow this service to be installed

  3. Hugo says:

    It didn’t worked for me 🙁

    When I call the install method, a black screen freezes saying:

    Installing assembly x

    Affected parameters are:

    assemblypath = y

    logFile = z

    And the log file has the same text

  4. shivaadabala says:

    Hi,

    It is working fine. Can you explain how to install the same service in the remote system.

    Thanks,

    Sams

  5. HelloWorld says:

    @Hugo: I do not have enough information from your error message. Is this a service application?

    @Sams: Sorry, I have not done remote install yet.

  6. John says:

    I tried running this via ASP.NET and got the following error:

    The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.

    I found a comment in the following which basically said needs to be run as administrator:

    http://msdn.microsoft.com/en-us/library/50614e95(VS.80).aspx

    Have you come across this problem and do you know a way to resolve it?

    Regards,

    John

  7. HelloWorld says:

    John,

    You need to be an administrator to install a service.

  8. Misha says:

    Alternatively, you can use online services like Installer.CodeEffects.com to compile and download installers for your Windows services in a couple of minutes. No InstallUtil or Windows Installer on is required on a target machine. You can even gather user’s input during installation by including custom fields in your installer. I thought this info might help you guys with your development.