Click here to Skip to main content
12,253,679 members (58,161 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

157.2K views
7.4K downloads
54 bookmarked
Posted

Creating a simple Windows Service

, 14 Sep 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
This article describes how to create a simple Windows Service using MS Visual Studio.

Introduction

I'll show how to create simple Windows Service in MS Visual Studio 2010 Express using no templates.

Background

The article Creating a Windows Service in C# helped me a lot, but it wasn't perfect. After I created a Windows Service and it worked, I decided to write an article to not forget how to create Windows Services.

Using the code

Start MS Visual Studio 2010 Express and create a new empty project.

Your Solution Explorer should now look like this:

2_after_project_creation.jpg

Then you have to add two classes: WinService.cs and ServiceInstaller.cs.

The WinService class should contains this code:

namespace WinServiceProject
{
    using System;
    using System.IO;

    class WinService : System.ServiceProcess.ServiceBase
    {
        // The main entry point for the process
        static void Main()
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun = 
              new System.ServiceProcess.ServiceBase[] { new WinService() };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
        }
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ServiceName = "WinService";
        }
        private string folderPath = @"c:\temp";
        /// <summary>
        /// Set things in motion so your service can do its work.
        /// </summary>
        protected override void OnStart(string[] args)
        {
            if(!System.IO.Directory.Exists(folderPath))
                System.IO.Directory.CreateDirectory(folderPath);

            FileStream fs = new FileStream(folderPath+"\\WindowsService.txt", 
                                FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(" WindowsService: Service Started at " + 
               DateTime.Now.ToShortDateString() + " " + 
               DateTime.Now.ToShortTimeString() + "\n");
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }
        /// <summary>
        /// Stop this service.
        /// </summary>
        protected override void OnStop()
        {
            FileStream fs = new FileStream(folderPath + 
              "\\WindowsService.txt", 
              FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(" WindowsService: Service Stopped at " + 
              DateTime.Now.ToShortDateString() + " " + 
              DateTime.Now.ToShortTimeString() + "\n");
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }
    }
}

This class contains two functions: OnStart and OnStop. I'll use them to show that our Windows Service is working. When the Service starts and stops, it will write a string to a file.

ServiceInstaller.cs should contain:

namespace WinServiceProject
{
    using System;

    /// <summary>
    ///     Summary description for ProjectInstaller.
    /// </summary>
    [System.ComponentModel.RunInstaller(true)]
    public class ProjectInstaller : System.Configuration.Install.Installer
    {
        /// <summary>
        ///    Required designer variable.
        /// </summary>
        //private System.ComponentModel.Container components;
        private System.ServiceProcess.ServiceInstaller serviceInstaller;
        private System.ServiceProcess.ServiceProcessInstaller 
                serviceProcessInstaller;

        public ProjectInstaller()
        {
            // This call is required by the Designer.
            InitializeComponent();
        }

        /// <summary>
        ///    Required method for Designer support - do not modify
        ///    the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.serviceInstaller = new System.ServiceProcess.ServiceInstaller();
            this.serviceProcessInstaller = 
              new System.ServiceProcess.ServiceProcessInstaller();
            // 
            // serviceInstaller
            // 
            this.serviceInstaller.Description = "My Windows Service description";
            this.serviceInstaller.DisplayName = "My WinService";
            this.serviceInstaller.ServiceName = "WinService";
            // 
            // serviceProcessInstaller
            // 
            this.serviceProcessInstaller.Account = 
              System.ServiceProcess.ServiceAccount.LocalService;
            this.serviceProcessInstaller.Password = null;
            this.serviceProcessInstaller.Username = null;
            // 
            // ServiceInstaller
            // 
            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
            this.serviceProcessInstaller,
            this.serviceInstaller});

        }
    }
}

In ServiceInstaller.cs, you can specify the Service's name, description, etc.

After creating the classes, add three references: System, System.Configuration.Install, and System.ServiceProcess. When you do that, your Solution Explorer will look like this:

3_after_classes_insertion.jpg

Now your project is complete. You can build it. In the bin\Release or bin\Debug folder, you will find the file WinServiceProject.exe. This is your Windows Service.

Now we need to add our service to other Windows Services and make it work. For this, we need to use InstallUtil. I found it in C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319. The last folder shows the Framework version. In the zip file attached, there are two bat files. install.bat installs our Service. It looks like this:

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\installutil.exe WinServiceProject.exe

pause

To uninstall the service, you have to use /u key with the InstallUtil utility. The second bat file named uninstall.bat looks like this:

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WinServiceProject.exe

pause

Now you have three files: WinServiceProject.exe, install.bat, and uninstall.bat. You have to now decide where your service will be. For testing and debugging purposes, I suggest you leave WinServiceProject.exe in the Debug or Release folder and copy the install.bat and uninstall.bat files so you can work in a single folder.

Notice! Before editing the project and rebuilding it, always stop your service. Otherwise you can get errors.

After you install your service, you can see it in local services:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Andrew Muza
Software Developer
Belarus Belarus
I'm Certified Force.com Developer, who have been building custom solutions using Force.com platform for last 4 years. This involves coding classes (batches, scheduled classes, email handlers), triggers and Visualforce pages (with Javascript, jQuery and CSS); adding/customizing standard and custom object. Mostly, I work on integration solutions.
(key words: Force.com, Salesforce, sObject, Apex, batch, trigger, governor limits, SOQL, Visualforce, integration, REST, Force.com IDE, Git)

Before Salesforce, for 4 years, I participated in application development using C#, Java, PHP, Qt and Action Script. Mostly, MS SQL and MySQL were used as data storage for applications.

You may also be interested in...

Comments and Discussions

 
QuestionYou can help me? Pin
naser.najafiazar24-May-15 5:20
membernaser.najafiazar24-May-15 5:20 
AnswerRe: You can help me? Pin
Andrew Muza24-Jun-15 3:18
professionalAndrew Muza24-Jun-15 3:18 
GeneralRe: You can help me? Pin
Member 1186868528-Jul-15 2:18
memberMember 1186868528-Jul-15 2:18 
GeneralRe: You can help me? Pin
Andrew Muza24-Nov-15 3:37
professionalAndrew Muza24-Nov-15 3:37 
GeneralMy vote of 5 Pin
Member 102163761-Apr-14 3:12
memberMember 102163761-Apr-14 3:12 
GeneralRe: My vote of 5 Pin
Andrew Muza24-Jun-15 3:20
professionalAndrew Muza24-Jun-15 3:20 
QuestionIs this article covering for cross windows versions? Pin
Flemming.M.Madsen22-Nov-13 2:59
memberFlemming.M.Madsen22-Nov-13 2:59 
AnswerRe: Is this article covering for cross windows versions? Pin
Andrew Muza24-Dec-13 19:37
memberAndrew Muza24-Dec-13 19:37 
QuestionStep by step guide to create windows service Pin
Xaheer Ahmed6-Nov-13 0:39
memberXaheer Ahmed6-Nov-13 0:39 
QuestionHI Pin
sajin jalal14-Oct-13 18:27
membersajin jalal14-Oct-13 18:27 
AnswerRe: HI Pin
Andrew Muza24-Dec-13 19:32
memberAndrew Muza24-Dec-13 19:32 
Questionthanks Pin
idrys29-Aug-13 4:39
memberidrys29-Aug-13 4:39 
AnswerRe: thanks Pin
Andrew Muza24-Dec-13 19:30
memberAndrew Muza24-Dec-13 19:30 
QuestionBeautiful! Works as intended. Pin
Member 102004299-Aug-13 14:55
memberMember 102004299-Aug-13 14:55 
AnswerRe: Beautiful! Works as intended. Pin
Andrew Muza24-Dec-13 19:29
memberAndrew Muza24-Dec-13 19:29 
QuestionGreat Job - Thank You!!! Pin
StinkyPants4-Oct-12 8:12
memberStinkyPants4-Oct-12 8:12 
SuggestionRun installutil.exe as administrator Pin
ddas-edEn11-Sep-12 6:28
memberddas-edEn11-Sep-12 6:28 
GeneralRe: Run installutil.exe as administrator Pin
Member 97988352-Jul-14 8:13
memberMember 97988352-Jul-14 8:13 
GeneralMy vote of 5 Pin
ddas-edEn11-Sep-12 2:45
memberddas-edEn11-Sep-12 2:45 
Answerthanks Pin
mtmam16-Jul-12 4:42
membermtmam16-Jul-12 4:42 
Answerthanks Pin
mtmam16-Jul-12 4:41
membermtmam16-Jul-12 4:41 
GeneralMy vote of 1 Pin
Kirill Kovalev6-Sep-10 3:07
memberKirill Kovalev6-Sep-10 3:07 
GeneralRe: My vote of 1 PinPopular
Andrii Muza6-Sep-10 4:12
memberAndrii Muza6-Sep-10 4:12 
GeneralRe: My vote of 1 Pin
Heriberto Lugo25-Jan-15 19:56
memberHeriberto Lugo25-Jan-15 19:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160426.1 | Last Updated 14 Sep 2010
Article Copyright 2010 by Andrew Muza
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid