C#: Create a Windows Services Tutorial

person Jason Huangfolder_openC#, Codelocal_offer, access_time December 25, 2008

Create a windows service in Visual Studio 2005 is a really simple task.

– You just need to start a new project Windows Service, write some code in service class to do something.
– Add an Service Installer class to the service project.
– Run .NET framework’s installutil.exe to install the new service.

1. in Visual Studio, File – New Project, then select Visual C# – Windows Service

2. Set some properties for the services: Open designer window for the service class (ie. Service1.cs), right click and select Properties. The most important property is “ServiceName”

3. Write some code to do something in this service.
( Select view Code for service class.) The most important functions are: OnStart() and OnStop(), which runs at a service’s startup and ending.

The following example have the service on start to write a little log entry to file specifying a message and system date time, and do the same thing for service ending.


protected override void OnStart(string[] args)
{
            // TODO: Add code here to start your service.
            WriteLog(System.DateTime.Now + ": Jason service started.");
            timer1.Enabled = true;
}
 
protected override void OnStop()
{
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            WriteLog(System.DateTime.Now + ": Jason service stopped.");
            timer1.Enabled = false;
}
 
private void WriteLog(string Msg)
{
            FileStream fs = new FileStream(LogFileName, FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(Msg);
            m_streamWriter.Flush();
            m_streamWriter.Close();
}

4. Now you need to add an installer class in order to install the service, without it the installutil will not work. Double click on the service code file to open designer (such as Service1.cs), in designer window, right click to get the Context Menu and select “Add Installer”. Now a necessary service installer class is added to your windows service project. Each time installutil.exe is run, this installer class will tell it how to install the service you wrote.

5. Now you can view the code for Installer class, the most important thing to remember is the serviceProcessInstaller‘s property Account.

ServiceProcessInstaller

You need to set it to LocalSystem because without specifying it or else will require other account priviledges in order to install the service. Select LocalSystem will install service locally.

ServiceProcessInstaller_Property

 

Usually the VS2005 generated installer class will have everything you need already written for you, you just need to to change the serviceProcessInstaller.Account to “LocalSystem”.

If you don’t set it to “LocalSystem”, when you install the service, it will prompt you for a user name and password.

prompt_for_user

If you prefer to do installer class manually, here is some info I learned from MS help file:
– Add a new installer class to service project. In the installer class
– Set the property RunInstaller to true: [RunInstaller(true)]
-Create instance of ServiceProcessInstaller which will specify option for installing service
-Create instance of ServiceInstaller for each service you want to install
– for serviceProcessInstaller, you need to set the Account, password, Username (leave username and password null if needed)
– Installers.Add(both the ServiceProcessInstaller and Whatever ServiceInstaller you use)

6. After you have the installer class and finish writing your service. Build it. You need to use the .NEt framework’s installutil to install service: the installutil.exe is usually in C:\Windows\Microsoft .NEt framwork\v2.xx\installutil.exe

type the command:
installutil.exe /i ServiceName.exe

to uninstall the service:
installutil.exe /u ServiceName.exe

7. After running installutil.exe you should your service showing up in Windows services. You can now start it or stop it.

The following example is a generated service installer class.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
 
namespace JasonService
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }
    }
 
...
            this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
            this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
            //
            // serviceProcessInstaller1
            //
            this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
            this.serviceProcessInstaller1.Password = null;
            this.serviceProcessInstaller1.Username = null;
            //
            // serviceInstaller1
            //
            this.serviceInstaller1.ServiceName = "JasonService";
            //
            // ProjectInstaller
            //
 
            this.Installers.Add(serviceInstaller1);
            this.Installers.Add(serviceProcessInstaller1);
        }
 
        private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
        private System.ServiceProcess.ServiceInstaller serviceInstaller1;

Comments

  1. Thanks, it’s helpful

  2. I genuinely like your blog and i really enjoy the fantastic top quality articles you are posting right here for cost-free for your online readers. Can you inform us which weblog operating system you are employing?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>