Creating a Windows Service in C#

I never needed a Windows Service application before, and I came across this type of project while googling for some other .Net capabilities, so I thought to give it a try. A Windows Service is a very useful toy when you need running tasks in background. How you do it:

Step 1: Create a new Windows Service project inside Visual Studio (2005 or 2008) and name it whatever you like:

01CreateWindowsServiceProject

Step 2: Rename the Service1.cs auto-generated class (I called it TestWindowsService); add a Timer object and edit OnStart and OnStop events added by Visual Studio:

using System;
using System.ServiceProcess;
using System.Timers;
using System.IO;

namespace TestWindowsService
{
    public partial class TestWindowsService : ServiceBase
    {
        Timer timer = new Timer(2000);

        public TestWindowsService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Enabled = true;
        }

        protected override void OnStop()
        {
            timer.Enabled = false;
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            using (TextWriter tw = new StreamWriter("C:\output" + DateTime.Now.ToString("yyMMddHHmmss") + ".txt"))
            {
                tw.WriteLine(“Text written at ” + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                tw.Flush();
                tw.Close();
            }
        }

    }
}

There are also other events that you can edit, like OnContinue, OnCustomCommand, OnPause, OnPowerEvent, OnShutdown; for this, check the definition of ServiceBase class, from which your service is derived.

Step 3: Add an installer for your service: in the design view for your service class, right click and choose Add Installer:

02WinServiceAddInstaller

Visual Studio will add an installer class, called ProjectInstaller.cs, having two components in design mode, serviceProcessInstaller and serviceInstaller. Modify the properties of these components as described below:

03WinServiceInstallerProps
04WinServiceProcInstallerProps

If you don’t set the Account of the serviceProcessInstaller component as LocalSystem, leaving it with User value instead, you’ll have to provide a user and a password on the installation process.

Step 4: Install the service you just created. For this, go to Start -> Programs -> Microsoft Visual Studio 2008 -> Visual Studio Tools -> Visual Studio 2008 Command Prompt, and use the following command on the new opened window:

InstallUtil /i TestWindowsService.exe

Be sure to provide the full path to your executable file. To uninstall the service, use

InstallUtil /u TestWindowsService.exe

Step 5: Start the service by going to Services console (from Administrative Tools under Windows XP) and start the service

05WinServiceServicesConsole

Note: The service will create several text files at every 2 seconds, so be sure to stop it after you tested its functionality.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: