Click here to Skip to main content
Click here to Skip to main content
Go to top

Windows Services Can Install Themselves

, 22 Nov 2007
Rate this:
Please Sign up or sign in to vote.
Never use the InstallUtil.exe utility that ships with the .NET SDK again.

Introduction

Using the InstallUtil.exe utility that ships with the .NET SDK can be a real pain. It's rarely in the PATH so you probably have to hunt down the utility when you are working on QA and production servers as I do. Installing a Windows Service should be easier. In this short article, I'll show you a way to make your Windows Services install themselves without needing InstallUtil.exe at all.

Assumptions

Let's assume that your service project has a service installer, a service process installer and a class derived from System.Configuration.Install.Installer already. If not, check out Mahmoud Nasr's excellent article on Windows Service development, then come back here.

Key Information

Thanks to Reflector for .NET by Lutz Roeder, it's easy to discover how the InstallUtil.exe utility does its job. After some setup, the InstallUtil.exe tool jumps to a method called InstallHelper in the ManagedInstallerClass in the System.Configuration.Install namespace. And what's really interesting is that the command line arguments passed to InstallUtil.exe as an array of strings are then passed directly to this helper method.

Well, this made me think, "If all InstallUtil.exe does is call the ManagedInstallerClass' InstallHelper method, why can't my service executable do the same thing to install itself on command?" The little class below makes it simple to do just that.

Using the Code

Create a new CS file in your service executable project containing the following code. You may also need to add a reference to the System.Configuration.Install.dll from the Global Assembly Cache if you don't already have one.

using System.Reflection;
using System.Configuration.Install;

namespace gotnet.biz.Utilities.WindowsServices
{
    public static class SelfInstaller
    {
        private static readonly string _exePath =
            Assembly.GetExecutingAssembly().Location;
        public static bool InstallMe()
        {
            try
            {
                ManagedInstallerClass.InstallHelper(
                    new string[] { _exePath } );
            }
            catch
            {
                return false;
            }
            return true;
        }

        public static bool UninstallMe()
        {
            try
            {
                ManagedInstallerClass.InstallHelper(
                    new string[] { "/u", _exePath } );
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}

Now you need to come up with some sort of convention for knowing when to invoke the installer. Below is just an example of how you might handle this in your Main() method, the entry point to your service. I like the convention of using -i or -install parameters to install the service and -u or -uninstall to uninstall it. I also like to use -c or -console to mean starting the application in a console rather than as a service. However, that's a topic for a different article.

using gotnet.biz.Utilities.WindowsServices;

namespace MyService.WinHost
{
    static class Program
    {
        public static void Main( string[] args )
        {
            if (args != null && args.Length == 1 && args[0].Length > 1
                && (args[0][0] == '-' || args[0][0] == '/'))
            {
                switch (args[0].Substring( 1 ).ToLower())
                {
                    default:
                        break;
                    case "install":
                    case "i":
                        SelfInstaller.InstallMe();
                        break;
                    case "uninstall":
                    case "u":
                        SelfInstaller.UninstallMe();
                        break;
                    case "console":
                    case "c":
                        MyConsoleHost.Launch();
                        break;
                }
            }
            else
                MyWinServiceHost.Launch();
        }
    }
}

Now, assuming my executable is named MyWinSvcHost.exe, I can invoke the installer by running:

C:\> MyWinSvcHost.exe -install

Or to uninstall my service, I would use this:

C:\> MyWinSvcHost.exe -uninstall

Other Ideas

This little bit of code called the SelfInstaller is full of possibilities. You could pass parameters to the InstallMe method to pass on to the ServiceProcessInstaller in your program, for example. Perhaps the domain name, user name and password used to start your service could be passed all the way from your Main() method to the ServiceProcessInstaller. Cool, right? I thought you would like that.

History

  • 22 Nov, 2007 - Initial publication

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

W. Kevin Hazzard
Web Developer
United States United States
After 16 years as an ardent C++ aficionado, Kevin switched to C# in 2001. Recently, Kevin's been dabbling in dynamically typed languages. Kevin is the Software Architect for Snagajob.com, the #1 source for hourly and part-time employment on the web.
 
Kevin loves welding, riding motorcycles and spending time with his family. Kevin has also been an adjunct professor teaching software engineering topics at a college in his hometown of Richmond, Virginia since 2000. Check out Kevin's technical blog at www.gotnet.biz for more goodies.

Comments and Discussions

 
GeneralMy vote of 5 Pinmembergogogoggg27-May-13 10:44 
GeneralMy vote of 5 PinmemberPavel Voronin24-May-13 6:43 
Questionwill it install without using newer version of installutil .exe incase our windows service is built in newer version only if latest client profile and runtime is intalled. PinmemberShabanaParveen4-Dec-12 21:42 
QuestionInstall two services from the same assembly PinmemberP. de Jong30-Aug-11 4:23 
GeneralService Template PinmemberSteve Foster (Havok Multimedia)26-Sep-10 11:09 
GeneralRe: Service Template PinmemberComplexityChaos14-Oct-10 6:26 
GeneralRe: Service Template PinmemberSteven D. Foster15-Oct-10 5:05 
GeneralNice but PinmentorGiorgi Dalakishvili6-Mar-10 10:18 
Questionhow do i get the service name from another exe Pinmemberjbencic19-Dec-09 15:56 
QuestionError 1053: The service did not respond to the start or control request in a timely fashion. Pinmemberkhayyam221-Sep-09 20:15 
GeneralTwo lines are confusing me please help Pinmemberkhayyam221-Sep-09 20:11 
GeneralConfused Steps Pinmemberkhayyam221-Sep-09 7:50 
GeneralDifferent Solution PinmemberDavid Hoyt13-Aug-09 6:56 
Generalno console output Pinmemberrapid2k211-Aug-09 15:52 
GeneralRe: no console output PinmemberErik Burger29-Jul-10 1:50 
GeneralAwesome! GUI and CLI! PinmemberBit-Smacker3-Aug-09 9:39 
GeneralManagedInstallerClass doesn't work to me PinmemberBizancio Spirit9-Jun-09 4:10 
GeneralAwesome post, thanks. Always wanted to know how that was done. PinmemberBuddy Stein1-Apr-09 7:11 
GeneralInstallHelper Doesn't release Service1.exe file after uninstall Pinmembersurf uk22-Jan-09 2:55 
Hi,
 
Excellent article! I have found non-command ways to do all things service related, apart from uninstalling...
 
I have created a helper service (Service1Updater) for my main service (Service1). Service1Updater does two things
-Checks a network folder to see if there's any updates for Service1 and installs them
-Checks to see if Service1 is running, if not then it tries to start it
 
The reason I'm using a service to do the updating:
-I don't want Service1 to fail when updating, I don't want to manually fix things
-I don't want any user interaction during updates
-I have a large cluster of computers to roll out the updates, I can't do it manually would take ages
-I want Service1 to stay alive if something unforeseen happens, so I use a helper process
 
The problem:
I use Service1Updater to copy new files -> stop Service1 -> uninstall Service1 -> delete old Service1 files -> copy new files -> install Service1 -> set Service1 properties -> start Service1.
 
Between "uninstall Service1 -> delete old Service1 files" I always get Access denied or UnauthorizedAccessException as the InstallHelper seams to still have a handle open on the old Service1. If I use a Process command then I have no problem deleteing the old files:
 
Process myProcess = new Process();
string path = @"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727";
myProcess.StartInfo.FileName = path + "\\InstallUtil.exe";
myProcess.StartInfo.Arguments = @"/u C:\Service1\Service1.exe";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
 
myProcess.WaitForExit(60000);
if (!myProcess.HasExited)
    myProcess.Kill();
myProcess.Close();
 
Although this works it would be nice to have an InstallHelper solution especially as InstallUtil maybe in a different location. Does anyone have any ideas? Would I have to host the InstallHelper in a different thread/process and wait for it to exit?
 
Cheers
 
Ross
 
not suitable for idiots

GeneralRe: InstallHelper Doesn't release Service1.exe file after uninstall PinmemberHJG0076-Feb-09 1:27 
GeneralRe: InstallHelper Doesn't release Service1.exe file after uninstall PinmemberVeener29-Apr-09 13:56 
General[Message Removed] PinmemberKatekortez25-Oct-08 9:30 
QuestionSetting ServiceProcessInstaller attributes PinmemberChris Newton28-May-08 2:45 
GeneralFor the console lovers ;-) PinmemberAleksei Nickolayev3-Mar-08 4:06 
GeneralRe: For the console lovers ;-) PinmemberW. Kevin Hazzard6-Mar-08 6:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 22 Nov 2007
Article Copyright 2007 by W. Kevin Hazzard
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid