Self Updating Windows Service

12 08 2009

So, having written a windows service, a neat thing to do is to get it to self-update.

Now, lets say you have installed the service after some work and it is running. The service can probably poll some server/web service and find out if updates are available. If yes, then you need to get the address of the new file/files and use C#’s webclient class to download the files.

Issues – The account under which the service runs can be the bottle neck. In general if you run a service as a particular user, password changes on a domain will not play well. On the other hand, running it as a NETWORK SERVICE (since you need to access network resources) will severely limit the folders you can touch.

The easy way out is to use the all powerful Local System account. You can pretty much do anything here… including writing into the windows folders.

OK, so your service is running under Local System. You download the new files using the service itself. Now comes the updating part. The trick is to simply replace the exe files. That way, you wont really have to bother about unregistering and re-registering the service. The service retains its registration/entry in the windows registry, and the next time the service starts, its a new exe that runs… Magic 🙂

So, easy thing to do is to generate a simple batch script using the old service. Having downloaded the new files (with some other name), generate the batch script, and start it up (System.Diagnostic.Process.Start). The batch file should

1. Stop the old service.

2. Delete the old service exe

3. Rename the new service exe to match the old exe name (in the same location too)

4. Start the service

5. Delete itself so that the whole procedure is clean 🙂

Now, service starting and stopping are permissions that Local System account  has… and since it spawned the batch script, this retains those permissions too… in general, each service has its own set of security descriptions (SDDL)… use sddltranslate or something like that to view a nice description of what sc sdshow outputs on the service…





One response

5 07 2013

There is certainly a lot to find out about this topic.
I love all of the points you have made.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: