Creating a Windows Service Using C#

Chvrsri
Posted by in C# category on for Advance level | Points: 250 | Views : 62083 red flag
Rating: 5 out of 5  
 5 vote(s)

Windows Services is the most important feature for the long standing applications to run services automatically soon after the system boots.We can manually control these Services by starting and stoping at a specific time.

Introduction

Windows Services are the most important feature for the long standing applications to run services automatically soon after the system boots.We can manually control these Services by starting and stoping at a specific time.Generally we can run these services on the server without any interference with the other users in the system.Here we can even restrict some specific services to be available only for specific users.

In this article iam going to explain -

  1. How to create a Windows Service?
  2. How to automatically populate the information about the service(StartTime,EndTime) in a text file?

I will divide this entire article into a step by step process with screen shots for better understanding purpose.

Step 1:

Open Visual Studio(My version 2008) and add a windows service project in this way

Step 2: 

Now open Service1.cs[Design] and have a right click you get view code option, select that option. So you will be getting Service1.cs file . Add this code to that file

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.ServiceProcess;

using System.Text;

using System.IO;

using System.Threading;

namespace WindowsService1

{

   public partial class Service1 : ServiceBase

{

 

public Service1()

{

   InitializeComponent();

}

 

static void run()

{

//while (true)

{

StreamWriter str = new StreamWriter("D:\\ContinuosLoop.txt", true);

str.WriteLine("Visit DotNetFunda Regularly");

str.Close();

}

}

Thread thr = new Thread(new ThreadStart(run));

 

protected override void OnStart(string[] args)

{

StreamWriter str = new StreamWriter("D:\\Log.txt", true);

str.WriteLine("Service started on : " + DateTime.Now.ToString());

str.Close();

thr.Start();

}

protected override void OnStop()

{

StreamWriter str = new StreamWriter("D:\\Log.txt", true);

str.WriteLine("Service stoped on : " + DateTime.Now.ToString());

str.Close();

thr.Abort();

}

 

}

}

 

Step 3:

We cannot directly run the service what we need to be done is add an installer. For that go back to Service1.cs[Design] file and right click and select AddInstaller option in this way

Now the Screen looks like this with 2 options this is ProjectInstaller.cs[Design]


 

Step 4:

Now we have 2 controls namely

      1) ServiceProcessInstaller1

            For this we have to change the Account Property to LocalSytem          

      2) ServiceInstaller1

For this we have to change the start type to manual and make sure you service name is well remembered.I gave ~~~SriService~~~ as in my example.

With this the coding part is completed now build the solution which will create the necessary files in bin folder.

Step 5:

As you all know inorder to run this service we have to install this service for that open VisualStudio Command Prompt. Go that the project path which was created by you untill the Project/bin/debug folder in this way

   Inorder to install we have to type installutil -i WindowsService1.exe at that path which looks like this

Step 6:

Now after successful installation you will recieve an message stating that "The Transacted install has completed" . If you get this that means your installation is successful now you can go and wacth the services folder to that go to control panel/perforamanceMaintainance/AdministartiveTools/Services.

At that palce you could see your service in this way

 

Step 7:

Now start the service. As per our coding after starting the service we create 2 text documents in the D: drive as per my example. Those are ContinousLoop.txt and Log.txt

In Log.txt the time and date of the service started and stopped will be displayed.

If you could observe i commented a line with while (true) in Service1.cs file. If we uncomment it, the line "Visit DotNetFunda Regularly" prints continuosly untill and unless we explicitly stop the service. so as i uncommented it that line will be displayed only once.

The final text documents will look like this

Conclusion

By this way we can create a Windows Service and can work with it accordingly. Hope I provided useful information in this article. Please provide your comment to imrpove this article if you feel so. Thanks!

Page copy protected against web site content infringement by Copyscape

About the Author

Chvrsri
Full Name: Radha Srikanth
Member Level: Silver
Member Status: Member,Moderator,MVP
Member Since: 10/22/2010 10:05:45 AM
Country: India
Thanks, Radha Srikanth

My self CH V R SRIKANTH having Professional Experience in Developing Desktop, Web based with ASP.NET, C#.NET, ADO.NET, C#, Jquery, Webservices, WCF and Objective C. I generally trade myself as an effective team player with proven strength in problem solving and strong analytical skills. Strong communication, interpersonal, learning and organizing skills matched with the ability to manage the stress, time and people effectively. Capable of working under pressure with willingness to lift sleeves up and get hands dirty on critical technical scenarios

Login to vote for this post.

Comments or Responses

Posted by: Vuyiswamb on: 12/18/2010 | Points: 25
Good article, i wrote an Article like this years ago here in DNF
Posted by: Chvrsri on: 12/19/2010 | Points: 25
Hi vuyiswamb,
Thanq so much!!!
Posted by: Vishalbedre on: 9/1/2011 | Points: 25
Good Article ...

Thanks
Posted by: Ksuresh on: 9/26/2011 | Points: 25
hi,

i fallowed your process so i got "the transacted install has completed" but in services "my service name" is not appearing .....

My purpose is to get data from database to text file using windows services.

thanks,
Posted by: Yuvarajchiyyodu on: 12/25/2011 | Points: 25
Hi,
First of all, I'm a new guy here. I have an issue cropping up. The transacted install has completed message did come up, but immediately The installation failed, and the roll back has been performed. message is displayed. And not surprisingly, I'm unable to find my service.
Can you please help?
TIA!

Posted by: thillairaja24-21331 on: 3/19/2013 | Points: 25
thanks sir

Posted by: Zaheerahmed on: 11/14/2013 | Points: 25
Here in this http://conceptf1.blogspot.com/2013/11/create-windows-service-step-by-step.html updated and detailed step by step guide to create windows service in c# available. Post also contain the information to create batch files.


Posted by: Maksim20032 on: 4/9/2015 | Points: 25
How to create a simple Windows Service in C# and Install it using Installutil

Enter here: http://www.docstorus.com/viewer.aspx?code=7c7ccc28-6503-4779-877e-f350faab6741

http://www.docstorus.com/viewer.aspx?code=7c7ccc28-6503-4779-877e-f350faab6741

Login to post response

Comment using Facebook(Author doesn't get notification)