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...”.
Step 2
Go to Visual C# -> ”Windows” -> ”Windows Service” then click OK.
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.
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.
- 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.
- 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.
- Create_ErrorFile
This method maintains a log of errors when an error occurs during the file copy.
-
-
-
- public static void Copy_Excelfile_And_Paste_at_anotherloaction()
- {
- try
- {
- string source = "D:\\DemoWebservice";
- string Destination = "D:\\DemoWebservice\\ExcelSheetCollection";
- string filename = string.Empty;
- if (!(Directory.Exists(Destination) && Directory.Exists(source)))
- return;
- string[] Templateexcelfile = Directory.GetFiles(source);
- foreach (string file in Templateexcelfile)
- {
- if (Templateexcelfile[0].Contains("Template"))
- {
- filename = System.IO.Path.GetFileName(file);
- Destination = System.IO.Path.Combine(Destination, filename.Replace(".xlsx", DateTime.Now.ToString("yyyyMMdd")) + ".xlsx");
- System.IO.File.Copy(file, Destination, true);
- }
- }
-
- }
- catch (Exception ex)
- {
- Create_ErrorFile(ex);
- }
-
- }
-
-
-
-
- public static void Create_ErrorFile(Exception exx)
- {
- StreamWriter SW;
- if (!File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txt_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")))
- {
- SW = File.CreateText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txt_" + DateTime.Now.ToString("yyyyMMdd") + ".txt"));
- SW.Close();
- }
- using (SW = File.AppendText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "txt_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")))
- {
- string[] str = new string[] { exx.Message==null?"":exx.Message.ToString(), exx.StackTrace==null?"":exx.StackTrace.ToString(),
- exx.InnerException==null?"":exx.InnerException.ToString()};
- for (int i = 0; i < str.Length; i++)
- {
- SW.Write("\r\n\n");
- if (str[i] == str[0])
- SW.WriteLine("Exception Message:" + str[i]);
- else if (str[i] == str[1])
- SW.WriteLine("StackTrace:" + str[i]);
- else if (str[i] == str[2])
- SW.WriteLine("InnerException:" + str[i]);}
-
- SW.Close();
- }
- }
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.
-
-
-
- public static void Create_ServiceStoptextfile()
- {
- string Destination = "D:\\DemoWebservice\\ServiceStopInforation";
- StreamWriter SW;
- if (Directory.Exists(Destination))
- {
- Destination = System.IO.Path.Combine(Destination, "txtServiceStop_" + DateTime.Now.ToString("yyyyMMdd") + ".txt");
- if (!File.Exists(Destination))
- {
- SW = File.CreateText(Destination);
- SW.Close();
- }
- }
- using (SW = File.AppendText(Destination))
- {
- SW.Write("\r\n\n");
- SW.WriteLine("Service Stopped at: " + DateTime.Now.ToString("dd-MM-yyyy H:mm:ss"));
- SW.Close();
- }
- }
Then I will call all these methods in the corresponding start and stop methods of the service.
-
-
-
- protected override void OnStart(string[] args)
- {
- int hour = DateTime.Now.Hour;
- int minute = DateTime.Now.Minute;
- if (hour == 12 && minute == 40)
- {
- Copy_Excelfile_And_Paste_at_anotherloaction_OnServiceStart();
- }
-
- }
-
-
-
-
- protected override void OnStop()
- {
- Create_ServiceStoptextfile();
- }
Step 6
Then go to the service designer window and right-click on design view then select “Add Installer”.
Right-click on the “ServiceInstaller1” and click “Properties”.
Change the service name and set StartType to Manual.
Then right-click on the “serviceProcessInstaller1” and click “Properties”.
Change the Account type to “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.
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.
Then we can see instal Windows Services here.
Go to Computer -> Manage as in the following:
Then go to ”Services and Applications” -> ”Services” as in the following:
See the installed services here.
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 the startup type and click OK.
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 stop output: Depending on the preceding written code one text file is created and it contains the Service stop time interval.
Thanks for reading my article.