Creating a Windows Service in C#

NOTE: The project name in this sample code is mcWebService which is a spelling mistake. I meant to put mcWinService. And now I don't want to change all the screen shots and code all over again. I hope it won't confuse you :).

Ok, its time for one more tutorial. This times pick is Windows Services. Creating Windows Services is not a big deal using C# and Visual Studio. Just follow few simple steps and you are all set to run and test your first Windows Service.

Windows Services is new name for NT Services you used to develop in previous versions of Visual Studio. This tutorial walks you through how to create and use your Windows Services. This Service writes some text to a text file when stop and start the service. The base idea is taken from MSDN but its more elaborated. You can modify it according to your needs.

Step 1. Create Skeleton of the Service

To create a new Window Service, pick Windows Service option from your Visual C# Projects, give your service a name, and click OK.

Create Windows Services

The result look like this. The Wizard adds WebService1.cs class to your project.

Create Windows Services

Set your ServiceName to your own name so it would be easier to recognize your service during testing OR you can set this property programmatically using this line this.ServiceName = "mcWinService";

This is the name you will be looking for later :).

Create Windows Services

The default code of WebService1.cs added by the Wizard looks like here

  1. namespace mcWebService   
  2. {   
  3. using System;   
  4. using System.Collections;   
  5. using System.Core;   
  6. using System.ComponentModel;   
  7. using System.Configuration;   
  8. using System.Data;   
  9. using System.Web.Services;   
  10. using System.Diagnostics;   
  11. using System.ServiceProcess;   
  12. public class WinService1 : System.ServiceProcess.ServiceBase   
  13. {   
  14. /// <summary>   
  15. /// Required designer variable.   
  16. /// </summary>   
  17. private System.ComponentModel.Container components;   
  18. public WinService1()   
  19. {   
  20. // This call is required by the WinForms Component Designer. InitializeComponent();   
  21. // TODO: Add any initialization after the InitComponent call   
  22. }   
  23. // The main entry point for the process   
  24. static void Main()   
  25. {   
  26. System.ServiceProcess.ServiceBase[] ServicesToRun;   
  27. // More than one user Service may run within the same process. To add   
  28. // another service to this process, change the following line to   
  29. / create a second service object. For example,   
  30. //   
  31. // ServicesToRun = New System.ServiceProcess.ServiceBase[] {new WinService1(), new   
  32. ySecondUserService()};   
  33. //   
  34. ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinService1() };   
  35. System.ServiceProcess.ServiceBase.Run(ServicesToRun);   
  36. }   
  37. /// <summary>   
  38. /// Required method for Designer support - do not modify   
  39. /// the contents of this method with the code editor.   
  40. /// </summary>   
  41. private void InitializeComponent()   
  42. {   
  43. components = new System.ComponentModel.Container();   
  44. this.ServiceName = "WinService1";   
  45. }   
  46. /// <summary>   
  47. /// Set things in motion so your service can do its work.   
  48. /// </summary>   
  49. protected override void OnStart(string[] args)   
  50. {   
  51. // TODO: Add code here to start your service.   
  52. }   
  53. /// <summary>   
  54. /// Stop this service.   
  55. /// </summary>   
  56. protected override void OnStop()   
  57. {   
  58. // TODO: Add code here to perform any tear-down necessary to stop your service.   
  59. }   
  60. }   
  61. }

Step 2. Add functionality to your service

As you saw WebService1.cs, there are two overridden functions OnStart and OnStop. The OnStart function executes when you start your service and the OnStop function gets execute when you stop a service. I write some text to a text file when you start and stop the service.

  1. protected override void OnStart(string[] args)   
  2. {   
  3.     FileStream fs =new FileStream(@"c:\temp\mcWindowsService.txt" ,   
  4.     FileMode.OpenOrCreate, FileAccess.Write);   
  5.     StreamWriter m_streamWriter =new StreamWriter(fs);   
  6.     m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);   
  7.     m_streamWriter.WriteLine(" mcWindowsService: Service Started \n");   
  8.     m_streamWriter.Flush();  
  9.     m_streamWriter.Close();   
  10. }   
  11. /// <summary>   
  12. /// Stop this service.   
  13. /// </summary>   
  14. protected override void OnStop()   
  15. {   
  16.     FileStream fs =new FileStream(@"c:\temp\mcWindowsService.txt" ,   
  17.     FileMode.OpenOrCreate, FileAccess.Write);   
  18.     StreamWriter m_streamWriter =new StreamWriter(fs);   
  19.     m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);   
  20.     m_streamWriter.WriteLine(" mcWindowsService: Service Stopped \n");   
  21.     m_streamWriter.Flush();  
  22.     m_streamWriter.Close();   
  23. }   
Step 3 - Install and Run the Service

Build of this application makes one exe, mcWinService.exe. You need to call installutil to register this service from command line.

installutil C:\mcWebService\bin\Debug\mcWebService.exe

You use /u option to uninstall the service.

installutil /u C:\mcWebService\bin\Debug\mcWebService.exe

Run the application

Step 4 - Start and Stop the Service

You need to go to the Computer Management to Start to start and stop the service. You can use Manage menu item by right clicking on My Computer. 

Manage Windows Services

Under Services and Applications, you will see the service mcWinService. Start and Stop menu item starts and stops the service.

Computer Management

Step 5: Test the Service

Go to your temp directory and see if text file is there with contents or not.

That's it.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.