Friday, January 07, 2005

How do I add install/uninstall option to a C# windows service program?


1. Add this to your service project


/*****************************

*

* install.cs

* Install the service

*

*/


using System;

using System.Collections;

using System.ComponentModel;

using System.Configuration.Install;

using System.ServiceProcess;

namespace MyService

{

[RunInstaller(true)]

public class MyInstaller : Installer

{

public MyInstaller()

{

ServiceProcessInstaller spi=new ServiceProcessInstaller();

spi.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

spi.Password = null;

spi.Username = null;

ServiceInstaller si = new ServiceInstaller();

si.StartType =ServiceStartMode.Automatic;
si.ServiceName = new MyService().ServiceName;

this.Installers.Add(spi);

this.Installers.Add(si);

}

}

}


2. Add System.Configuration.Install reference to the project


3. The main function shuold look like this


// The main entry point for the process

static void Main(string[] args)

{

string opt=null;


// install the service if user entered "ServiceMonitor /install"

if(args.Length >0 )

{

opt=args[0];

}

if(opt!=null && opt.ToLower()=="/install")

{

try

{


TransactedInstaller ti= new TransactedInstaller();

MyInstaller mi = new MyInstaller();

ti.Installers.Add(mi);

String path=String.Format("/assemblypath={0}",

System.Reflection.Assembly.GetExecutingAssembly().Location);

String[] cmdline={path};

InstallContext ctx = new InstallContext("",cmdline);

ti.Context =ctx;

ti.Install(new Hashtable());

}

catch(System.Exception exp)

{

Console.WriteLine(exp);

}

}



// uninstall the service if user entered "ServiceMonitor /uninstall"

else if (opt !=null && opt.ToLower()=="/uninstall")

{

try

{

TransactedInstaller ti=new TransactedInstaller();

MyInstaller mi=new MyInstaller();

ti.Installers.Add(mi);

String path = String.Format("/assemblypath={0}",

System.Reflection.Assembly.GetExecutingAssembly().Location);

String[] cmdline={path};

InstallContext ctx = new InstallContext("",cmdline);

ti.Context=ctx;

ti.Uninstall(null);

}

catch(System.Exception exp)

{

Console.WriteLine(exp);

}



}


if(opt==null) // e.g. ,nothing on the command line

{

System.ServiceProcess.ServiceBase[] ServicesToRun;



ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyService() };


System.ServiceProcess.ServiceBase.Run(ServicesToRun);

}


}