Tuesday, October 21, 2008

Install / Uninstall / start / stop Windows Service Programmatically

Necessity is mother of inventions one of my requirements turned out to be a blog entry again........

How to Install / Uninstall / start / stop Windows Service Programmatically
Sometimes you may want to install / Uninstall a Windows Service programmatically, but the target machine does not have InstallUtil.exe.

Install / Unistall:

To install/Uninstall 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);
}

Check for the service's startup type if disable. Keep it either Automatic or Manual.

Start and Stop of service

using System.ServiceProcess;
ServiceController controller = new ServiceController();
controller.MachineName = ".";
controller.ServiceName = "IISADMIN";
string status = controller.Status.ToString();
// Stop the servicecontroller.Stop();
// Start the servicecontroller.Start();

Happy Coding!!!!!

1 comment:

 
web counter
Download a free hit counter here.