65.9K
CodeProject is changing. Read more.
Home

Windows Service Updater

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.73/5 (16 votes)

Sep 12, 2006

viewsIcon

52622

Simple way to update a running windows service

Introduction

This simple code shows how to update a Windows service without having to go through the manual process of starting/stopping it.

To make it work you put your new service .exe file in a specified directory and then the service itself looks at the file system. Once it sees an update for itself, it then calls serviceupdate.exe to stop the service, replace the executable, and then restart
the service again. This saves plenty of time when having to do lots of updates to a service.

These go in the windows service:

private void IntializeFileSystemWatcher()
{
    System.IO.FileSystemWatcher newexe=new   System.IO.FileSystemWatcher(
        "c:\\services\\Updates","newservice.exe");
    newexe.Created += new FileSystemEventHandler(NewExecutable);
    newexe.EnableRaisingEvents = true;
}
private void NewExecutable(object source, FileSystemEventArgs e)
{
    Process.Start("c:\\services\\ServiceUpdate.exe","newservice");
}
protected override void OnStart(string[] args)
{
    IntializeFileSystemWatcher();
} 

Contents of serviceupdate.exe:

static void Main(string[] args)
{
    if (args.Length == 0)
        return;
    string filename=args[0];

    System.ServiceProcess.ServiceController target = new 
        System.ServiceProcess.ServiceController(filename);

    target.Stop();
    while(target.Status != 
        System.ServiceProcess.ServiceControllerStatus.Stopped)
    {
        target.Refresh();
    }
    Thread.Sleep(2000);
    File.Delete("c:\\services\\Updates\\" + filename + ".exe");

    File.Move("c:\\services\\Updates\\" + filename + 
        ".exe","c:\\services\\" + filename + ".exe");
    target.Start();
}