Click here to Skip to main content
Click here to Skip to main content

Windows Services Can Install Themselves

By , 22 Nov 2007
 

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)

About the Author

W. Kevin Hazzard
Web Developer
United States United States
Member
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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralDifferent SolutionmemberDavid Hoyt13 Aug '09 - 6:56 
I had my own solution back in 2005 for this: Self installing .NET service using the Win32 API[^]
 
It uses the native API and the latest versions (available through CodePlex as part of a greater project: http://www.codeplex.com/aspnetSuite[^]) support UAC and 32/64 bit support on Windows, Vista, and beyond. It will auto-detect if it's not installed and attempt to install it. You can also provide command line options to install, uninstall, etc. It also provides install/uninstall/start/stop/etc. utils for any service on the system (each w/ UAC support, if needed) and will automatically degrade to a typical console-based application if running in user interactive mode. It also provides more control than the .net framework-provided one in terms of what messages you can respond to (e.g. system shutdown, power states, etc.), your error handling capabilities, etc.
 
You can write an entire service w/ all of that functionality w/ ~2 methods.
Generalno console outputmemberrapid2k211 Aug '09 - 15:52 
After trying your suggestions inside a windows service I'm programming, there is no console output. Surely it has something to do with the type of the project (window service instead of console application), but I don't know what to change in the project properties to get something. Of course, if I start with a console appl I get no service Smile | :) Confused | :confused:
 
pd.- by console output I mean everything that gets out from system.console.writeline(), for example.
 
Thanks in advance for any suggestion...
GeneralRe: no console outputmemberErik Burger29 Jul '10 - 1:50 
Royally late but yes, it does have to do with the project type. If you go to Properties, Application and change the Output type to 'Console Application' you'll get the output you're missing.
Reverse Alchemy - http://www.reversealchemy.net

GeneralAwesome! GUI and CLI!memberBit-Smacker3 Aug '09 - 9:39 
I combined the enhancements by Aleksei Nickolayev and Ashley van Gerven, and now have my services accepting command line switches and offering to install or uninstall if launched interactively. This is the best! No more batch files!
 
Thanks for a great article, and thanks to the other users for the great enhancement ideas!
 
How could anyone not vote 5? Cool | :cool:
GeneralManagedInstallerClass doesn't work to mememberBizancio Spirit9 Jun '09 - 4:10 
I have a problem Frown | :( I can install a Windows service by InstallUtil but I can't do it when I try to do it with ManagerInstallerClass. It's strange, I reflected the Code (is the same that InstallUtil) and it doesn't work. Context data? This is My Code:
 
static void Main(string[] args)
{
string path = @"";
 
MainK(new string[] { path });
}
 
public static int MainK(string[] args)
{
Thread.CurrentThread.CurrentUICulture = CultureInfo.CurrentUICulture.GetConsoleFallbackUICulture();
if (((Console.OutputEncoding.CodePage != 0xfde9) && (Console.OutputEncoding.CodePage != Thread.CurrentThread.CurrentUICulture.TextInfo.OEMCodePage)) && (Console.OutputEncoding.CodePage != Thread.CurrentThread.CurrentUICulture.TextInfo.ANSICodePage))
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
}
Assembly.GetEntryAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), true);
try
{
ManagedInstallerClass.InstallHelper(args);
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
return -1;
}
return 0;
}
GeneralAwesome post, thanks. Always wanted to know how that was done.memberBuddy Stein1 Apr '09 - 7:11 
Awesome post, thanks. Always wanted to know how that was done.
GeneralInstallHelper Doesn't release Service1.exe file after uninstallmembersurf 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 uninstallmemberHJG0076 Feb '09 - 1:27 
Hi Ross,
I have the same problem and didn't find any solution for this Frown | :-(
 
Regards
Jürgen
GeneralRe: InstallHelper Doesn't release Service1.exe file after uninstallmemberVeener29 Apr '09 - 13:56 
Hi Guys,
 
I ran into this problem and found a solution by running the uninstall method in another AppDomain similar to the way it is documented here.
http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic48232.aspx[^]
 
Not only does it put a lock on the file when you uninstall it, also, if you check to see if it is a installable service (using AssemblyInstaller.CheckIfInstallable) then you cannot delete the file either unless you use this method.
 
Enjoy...
General[Message Removed]memberKatekortez25 Oct '08 - 9:30 
Spam message removed
QuestionSetting ServiceProcessInstaller attributesmemberChris Newton28 May '08 - 2:45 
Hi, would you mind providing an example of how you would use the command line switches to set properties of the underlying ServiceProcessInstaller object.
 
Thanx...
GeneralFor the console lovers ;-)memberAleksei Nickolayev3 Mar '08 - 4:06 
First of all, THANK YOU for your article. It is really useful.
 
I have one little improvement. In case of your code user must know what switches service executable accepts. I suppose it's a good idea to show all acceptable switches to user when the service was started from console, not from SCM.
The method that I use to determine how service was started is quite simple — checking the value of Environment.UserInteractive.
 
Code:
        static void Main(string[] args)
        {
            // Started by user
            if (Environment.UserInteractive)
            {
                // Show version information
                Console.Write(Environment.NewLine + System.Reflection.Assembly.GetExecutingAssembly().FullName + ".");
 
                // Parsing command line
                if (args != null && args.Length >= 1)
                {
                    if (args[0].ToLower() == "/i")
                    {
                        // InstallHelper with /u switch set adds CRLF here, but with /i switch set it does not. So...
                        Console.WriteLine();
                        
                        installMyService();
                        return;
                    }
                    if (args[0].ToLower() == "/u")
                    {
                        uninstallMyService();
                        return;
                    }
                }
 
                // Show usage
                Console.WriteLine(Environment.NewLine + Environment.NewLine + "Usage: MyService.exe [/i | /u]" + Environment.NewLine + Environment.NewLine + "Where:");
                Console.WriteLine("       /i - install service;");
                Console.WriteLine("       /u - uninstall service.");
            }
            // Started by SCM
            else
            {
                ServiceBase.Run(new MyService());
            }
        }
 
        static void installMyService()
        {
            try
            {
                // "/LogFile=" - to suppress install log creation
                ManagedInstallerClass.InstallHelper(new string[] { "/LogFile=", Assembly.GetExecutingAssembly().Location });
            }
            catch
            {
            }
        }
 
        static void uninstallMyService()
        {
            try
            {
                // "/LogFile=" - to suppress uninstall log creation
                ManagedInstallerClass.InstallHelper(new string[] { "/u", "/LogFile=", Assembly.GetExecutingAssembly().Location });
            }
            catch
            {
            }
        }

GeneralRe: For the console lovers ;-)memberW. Kevin Hazzard6 Mar '08 - 6:51 
Very nice, Aleksei. Nice addition.
 
Thanks,
 

GeneralGreat articlemembersrinath g nath30 Dec '07 - 18:09 
Great article
GeneralInstall on first run [modified]memberAshley van Gerven21 Dec '07 - 17:55 
Firstly, very nice simple solution - thanks for sharing that tip. I decided to try it out and came up with the idea of installing the service if it's not already installed (i.e. just double click it in Explorer, and confirm whether or not to install it). Worked well for me, using this code:
 
if (args.Length == 0)
{
	ServiceController sc = new ServiceController("AshFMS2");
	try
	{
		string s = sc.Status.ToString();  // throws exception if service does not exist
	}
	catch
	{
		if (System.Windows.Forms.MessageBox.Show("Install this service?          ", "Confirm", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
		{
			SelfInstaller(SelfInstallOptions.Install);
			return;
		}
	}
}
else
{
	switch (args[0])
	{
		case "-i" :
		case "/i" :
			SelfInstaller(SelfInstallOptions.Install);
			return;
		case "-u" :
		case "/u" :
			SelfInstaller(SelfInstallOptions.Uninstall);
			return;
	}
}
 
BTW SelfInstaller is my method containing code based on yours.
 
------------------------------
My Latest CP article: SmartPager - a Flickr-style pager control with go-to-page popup layer.
modified on Saturday, December 22, 2007 12:01:11 AM

GeneralRe: Install on first runmemberW. Kevin Hazzard26 Dec '07 - 3:54 
Very good, Ashley. Nice extension of the concept. It would be interesting to make
your code detect the version of the installed service and upgrade it on demand.
 

GeneralRe: Install on first runmemberAshley van Gerven26 Dec '07 - 4:13 
I think if you stop the service you can replace the .exe no problem.
 
cheers
Ashley
 

"For fifty bucks I'd put my face in their soup and blow." - George Costanza

CP article: SmartPager - a Flickr-style pager control with go-to-page popup layer.


GeneralCan't start service.memberRicky27 Nov '07 - 14:09 
..When I try to start the command line installed service from the Computer Management tool,
I get a Services message box (!), quoting "Could not start the MyCLI_Service on Local Computer. Error 3: The system cannot find the path specified." Huh?
..The CLI Install appears to have gotten the correct path, so what gives?
..The Uninstall appears to work. (I have done it several times.Wink | ;-)
..The original project was setup as a Windows Service project and the solution included a setup/deployment project which got the service into the Services list of the Computer Management tool. This original version of the service could be started, paused (required a property setting change), and stopped.
 
Look sharp, be sharp, see sharp!

GeneralRe: Can't start service.memberW. Kevin Hazzard29 Nov '07 - 10:00 
I suppose I would start by looking around in the registry at HKLM\System\CurrentControlSet\Services to see how your service got registered. Is the ImagePath value OK for your service?
 

GeneralRe: Can't start service.memberRicky30 Nov '07 - 12:44 
The ImagePath appears okay. However, I am using a fake drive/path, that is, I have substituted a C: path with J: drive. I will try placing all the files in a real path on the C: drive. Will update results. Thanks for feedback. Ricky Confused | :confused:
 
Look sharp, be sharp, see sharp!

GeneralRe: Can't start service.memberRicky30 Nov '07 - 12:54 
It works!!! No substituted drive pathing allowed. *.msi files have similar problems.
Now I can breathe and thank you for a great article.
Ricky Big Grin | :-D
 
Look sharp, be sharp, see sharp!

GeneralI took a different tack [modified]memberPIEBALDconsult26 Nov '07 - 16:12 
The EXE takes command line parameters. If the first parameter is "INSTALL" then it does:
 
System.Diagnostics.Process.Start
(
    "INSTALLUTIL"
,
    "\"" + System.Windows.Forms.Application.ExecutablePath + "\""
) ;
 
With similar code for UNINSTALL. START and STOP can also be done from the command line.
 
(I chose this method when I wrote my first Windows service three years ago and haven't revisited the code since, I guess I'll have to now.)
 

 
-- modified at 9:33 Thursday 29th November, 2007
 
SWEET! Thanks!
GeneralRe: I took a different tackmembercplas14 Jan '09 - 14:04 
The whole point of this article is NOT to use InstallUtil.
GeneralYou can go further (an alternative approach)memberOleg Shilo26 Nov '07 - 15:18 
Good job.
 
I do agree with all your reasons for improving standard service installation approach. Using InstallUtil.exe in the way MS intended is a pain. I think your approach is great however you can go even further (and in "more standard" way) by directly addressing the issue of "not knowing" InstallUtil.exe path. After all you have already guessed where to get help - Reflection.
 
The following code represents complete solution for service self-installation. It uses InstallUtil.exe thus all its functionality (e.g. logging to file) is still available.
 
I've been using this approach for more than a year and I had no problems with it. It is no surprise as it is exactly the way of service installation, which is regarded as a standard service installation. I just use a couple of tricks to get path information at runtime and one of these tricks is the same as yours.
 
BTW AppDomain.ExecuteAssembly even allows you to see InstallUtil.exe console output as yours.
Also note that InstallUtil.exe is executed in the same process space as the service application so no new (external) process is started.

 
string installUtil = Path.Combine(Path.GetDirectoryName(typeof(string).Assembly.Location), 
                                  "InstallUtil.exe");

AppDomain dom = AppDomain.CreateDomain("temp");

if (args[0].ToLower() == "/i")
{
    dom.ExecuteAssembly(installUtil, null, new string[] { 
        "/LogFile="
        "/LogToConsole=false"
        Application.ExecutablePath });
}
else if (args[0].ToLower() == "/u")
{
    dom.ExecuteAssembly(installUtil, null, new string[] { 
        "/u"
        "/LogFile="
        "/LogToConsole=false"
        Application.ExecutablePath });
}

 
Cheers,
Oleg
GeneralRe: You can go further (an alternative approach)membertag200126 Nov '07 - 18:24 
launching an external exe is ALWAYS inferior to a direct API call. I'd go with the article author's approach long before these fragile "launch the command line tool" approach.

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

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