Windows Services in C#

This article explains Windows Services in the .Net Framework. We will learn the following points.

  • Purpose of Windows Services.
  • How to create Windows Services in the .Net Framework.

Here, I will explain Windows Services with a simple demo. The design of my demo is it copies an Excel file from one location to another location on disk on a daily basis at a specific time.

Purpose of Windows Services

There are multiple purposes of Windows Services.

  • If we need to run a task on the server on a daily basis at a specified time without manual interaction then you can use Windows Services for that.

  • Tasks related to backup purposes you can do using Windows Services.

  • Tasks related to monitoring you can do using Windows Services.

  • Using this you can schedule your task at a specific time of the everyday, for example send mail, create a file and so on.

Windows Services run in the background like the SQL Server Agent service and some antivirus services run in the background.

How to create Windows Services in .Net framework

Step 1

Go to Visual Studio 2012 then select “File” -> ”New” -> ”Project...”.

new project

Step 2

Go to Visual C# -> ”Windows” -> ”Windows Service” then click OK.

windows service

Step 3

You will then see this window appear after creating the project.

Click here to switch to code view.

This is the design view of the service. Here you can drag and drop some control for user interaction if required. You can drag and drop a Progress Bar in design view depending on you what you need to do.

how to switch to code view

Step 4

When you click on Switch to code view then you will see two the override methods Onstart and Onstop in the service.cs file.

cs code

  • OnStart Method: Here you put your piece of code that you want to execute when the Service starts.

  • OnStop Method: Here you put your piece of code that you want to execute when the Service stops.

Step 5

Now I provide my code here.

I will write two methods for copying the Excel file from one disk location to another disk location.

Methods: All these methods are used by the onStart method.

  1. Copy_Excelfile_And_Paste_at_anotherloaction_OnServiceStart

    The purpose of this method is to copy an Excel file from on disk location to another disk location.

  2. Create_ErrorFile

    This method maintains a log of errors when an error occurs during the file copy.
    1. /// </summary>
    2. /// The purpose of this method is to copy Excel sheet from one location to another location at specified time period.  
    3. /// </summary>  
    4. public static void Copy_Excelfile_And_Paste_at_anotherloaction()  
    5. {  
    6.     try  
    7.     {  
    8.         string source = "D:\\DemoWebservice";  
    9.         string Destination = "D:\\DemoWebservice\\ExcelSheetCollection";  
    10.         string filename = string.Empty;  
    11.         if (!(Directory.Exists(Destination) && Directory.Exists(source)))  
    12.             return;  
    13.         string[] Templateexcelfile = Directory.GetFiles(source);  
    14.         foreach (string file in Templateexcelfile)  
    15.         {  
    16.             if (Templateexcelfile[0].Contains("Template"))  
    17.             {  
    18.                 filename = System.IO.Path.GetFileName(file);  
    19.                 Destination = System.IO.Path.Combine(Destination, filename.Replace(".xlsx", DateTime.Now.ToString("yyyyMMdd")) + ".xlsx");  
    20.                 System.IO.File.Copy(file, Destination, true);  
    21.             }  
    22.         }  
    23.   
    24.     }  
    25.     catch (Exception ex)  
    26.     {  
    27.         Create_ErrorFile(ex);  
    28.     }  
    29.   
    30. }  
    31. /// <summary>  
    32. /// purpose of this method is to maintain error log in text file.  
    33. /// </summary>  
    34. /// <param name="exx"></param>  
    35. public static void Create_ErrorFile(Exception exx)  
    36. {  
    37.     StreamWriter SW;  
    38.     if (!File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txt_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")))  
    39.     {  
    40.         SW = File.CreateText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txt_" + DateTime.Now.ToString("yyyyMMdd") + ".txt"));  
    41.         SW.Close();  
    42.     }  
    43.     using (SW = File.AppendText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txt_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")))  
    44.     {  
    45.         string[] str = new string[] { exx.Message==null?"":exx.Message.ToString(), exx.StackTrace==null?"":exx.StackTrace.ToString(),  
    46.             exx.InnerException==null?"":exx.InnerException.ToString()};  
    47.         for (int i = 0; i < str.Length; i++)  
    48.         {  
    49.             SW.Write("\r\n\n");  
    50.             if (str[i] == str[0])  
    51.                 SW.WriteLine("Exception Message:" + str[i]);  
    52.             else if (str[i] == str[1])  
    53.                 SW.WriteLine("StackTrace:" + str[i]);  
    54.             else if (str[i] == str[2])  
    55.                 SW.WriteLine("InnerException:" + str[i]);}  
    56.           
    57.         SW.Close();  
    58.     }  
    59. }  
    Then I will write the code for the onStop method of the Service.

Here I have create one method:

1. Create_ServiceStoptextfile

The purpose of this method is to maintain the service stop time in a text file.

  1. /// </summary>
  2. /// The purpose of this method is maintain service stop information in text file.  
  3. /// </summary>  
  4. public static void Create_ServiceStoptextfile()  
  5. {  
  6.     string Destination = "D:\\DemoWebservice\\ServiceStopInforation";  
  7.     StreamWriter SW;  
  8.     if (Directory.Exists(Destination))  
  9.     {  
  10.         Destination = System.IO.Path.Combine(Destination, "txtServiceStop_" + DateTime.Now.ToString("yyyyMMdd") + ".txt");  
  11.         if (!File.Exists(Destination))  
  12.         {  
  13.             SW = File.CreateText(Destination);  
  14.             SW.Close();  
  15.         }  
  16.     }  
  17.     using (SW = File.AppendText(Destination))  
  18.     {  
  19.         SW.Write("\r\n\n");  
  20.         SW.WriteLine("Service Stopped at: " + DateTime.Now.ToString("dd-MM-yyyy H:mm:ss"));  
  21.         SW.Close();  
  22.     }  
  23. }  
Then I will call all these methods in the corresponding start and stop methods of the service.

 

  1. /// </summary>
    /// OnStart Method write code if we want to execute code when service is started.
      
  2. /// </summary>  
  3. /// <param name="args"></param>  
  4. protected override void OnStart(string[] args)  
  5. {  
  6.     int hour = DateTime.Now.Hour;  
  7.     int minute = DateTime.Now.Minute;  
  8.     if (hour == 12 && minute == 40)  
  9.     {  
  10.         Copy_Excelfile_And_Paste_at_anotherloaction_OnServiceStart();  
  11.     }  
  12.   
  13. }  
  14. /// <summary>  
  15. /// OnStop Method write code if we want to execute the particular code when service is Stop.  
  16. /// </summary>  
  17. /// <param name="args"></param>  
  18. protected override void OnStop()  
  19. {  
  20.     Create_ServiceStoptextfile();  
  21. }  

Step 6

Then go to the service designer window and right-click on design view then select “Add Installer”.

add installer

Right-click on the “ServiceInstaller1” and click “Properties”.

serviceblog

Change the service name and set StartType to Manual.

properties

Then right-click on the “serviceProcessInstaller1” and click “Properties”.

serviceProcessInstaller

Change the Account type to “LocalSystem”.

LocalSystem

Then rebuild the project.

After successfully building the project we need to install the Windows Service.

Step 7

Install the service.

Run the Visual Studio 2012 command promt as administrator.

administrator

cmd

Here specify this line for the installation purposes of the Windows Service.

Installutil [path of your Windows Service exe file]

For example:

installutil D:\Demo\DemoWindoserviceBlog\DemoWindoserviceBlog\bin\Debug\DemoWindoserviceBlog.exe

After successful installation we see this output in the command promt regarding the installation information of the service.

command promt

Then we can see instal Windows Services here.

Go to Computer -> Manage as in the following:

manage

Then go to ”Services and Applications” -> ”Services” as in the following:

installed service

See the installed services here.

services and applications

Then right-click on the Service and manually start the Service. If you want to start the Service automatically then change startup type of the Service here.

change startup type

Change the startup type and click OK.

startup type

UnInstall Windows Services using this command:

Installutil /u [Path of application exe file]

Installutil /u D:\Demo\DemoWindoserviceBlog\DemoWindoserviceBlog\bin\Debug\DemoWindoserviceBlog.exe

Then see the service start output here depending on the code written above.
I have written the code in the start method for copying the Excel file from one location and paste at another location.

The following is the Service start output:

Service Start Output

Service stop output: Depending on the preceding written code one text file is created and it contains the Service stop time interval.

stop time interval

Thanks for reading my article.

 


Similar Articles