DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Phased Migration Strategy for Zero Downtime in Systems
  • Feature Flags in .NET 8 and Azure
  • Implementing CRUD Operations With NLP Using Microsoft.Extensions.AI
  • Launching Pega Web Mashup Forms on a Secure Static Website With AWS S3

Trending

  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • Next-Gen IoT Performance Depends on Advanced Power Management ICs
  • Building Resilient Networks: Limiting the Risk and Scope of Cyber Attacks
  • Optimizing Software Performance for High-Impact Asset Management Systems
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Create Windows Services in C#

Create Windows Services in C#

In this post, we go over how to get started using C# and .NET by creating a basic Windows service with these technologies.

By 
Faisal Pathan user avatar
Faisal Pathan
·
Jul. 09, 18 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
491.2K Views

Join the DZone community and get the full member experience.

Join For Free

Here I’m going to explain Windows Services in C# .NET.

  • Introduction of Windows Services.
  • How to create Windows Services in C# .NET.

Introduction

Windows Services normally start when the OS boots and runs an application in the background. Windows Services executes applications in its own session. It either starts automatically or we can manually pause, stop, and restart it.

You can find services in the following ways

  • Go to Control Panel select “Services” inside “Administrative Tools.”
  • Open Run window (Window + R), type in services.msc, and press enter.

How to Create a Windows Service

Step 1

Open Visual Studio, go to File > New and select Project. Now select a new project from the Dialog box and select “Window Service” and click on the OK button.

windows service

Step 2

Go to Visual C# -> ”Windows Desktop” -> ”Windows Service,” give your project an appropriate name and then click OK

windows service 

Once you click OK, the below screen will appear, which is your service

windows service

Step 3

Right-click on the blank area and select “Add Installer.”

Adding Installers to the Service

Before you can run a Windows Service, you need to install the Installer, which registers it with the Service Control Manager.

windows service

After Adding Installer, ProjectInstaller will add in your project and ProjectInstakker.cs file will be open. Don’t forget to save everything (by pressing ctrl + shift + s key)

windows service

The Solution Explorer looks like this:

windows service 

Step 4

Right click on blank area and select “View Code”

windows service

Step 5

Its has a Constructor, which contains the InitializeComponent method.

The InitializeComponent method contains the logic which creates and initializes the user interface objects dragged on the form's surface and provides the Property Grid of Form Designer.

Very important: Don't ever try to call any method before the call of InitializeComponent method.  windows service

Step 6

Select the InitializeComponent method and press the F12 key to go the definition.

windows service 

Step 7

Now add the below line while installing the service:

this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

You also can add a description and display the service name (optionally).

this.serviceInstaller1.Description = "My First Service demo";  
this.serviceInstaller1.DisplayName = "MyFirstService.Demo";  

windows service

Step 8

In this step, we will implement a timer, and code to call a service at a given time. We will create a simple write in a text file.

windows service

Service1.cs class 

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Diagnostics;  
using System.IO;  
using System.Linq;  
using System.ServiceProcess;  
using System.Text;  
using System.Threading.Tasks;  
using System.Timers;  

namespace MyFirstService {  
    public partial class Service1: ServiceBase {  
        Timer timer = new Timer(); // name space(using System.Timers;)  
        public Service1() {  
            InitializeComponent();  
        }  
        protected override void OnStart(string[] args) {  
            WriteToFile("Service is started at " + DateTime.Now);  
            timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);  
            timer.Interval = 5000; //number in milisecinds  
            timer.Enabled = true;  
        }  
        protected override void OnStop() {  
            WriteToFile("Service is stopped at " + DateTime.Now);  
        }  
        private void OnElapsedTime(object source, ElapsedEventArgs e) {  
            WriteToFile("Service is recall at " + DateTime.Now);  
        }  
        public void WriteToFile(string Message) {  
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";  
            if (!Directory.Exists(path)) {  
                Directory.CreateDirectory(path);  
            }  
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";  
            if (!File.Exists(filepath)) {  
                // Create a file to write to.   
                using(StreamWriter sw = File.CreateText(filepath)) {  
                    sw.WriteLine(Message);  
                }  
            } else {  
                using(StreamWriter sw = File.AppendText(filepath)) {  
                    sw.WriteLine(Message);  
                }  
            }  
        }  
    }  
}  

Code explanation - the above code will call a service every 5 seconds and create a folder if none exist and write our message.

Step 9: Rebuild Your Application

Right-click on your project or solution and select Rebuild.


windows service

Step 10

Search “command Prompt” and run the program as an administrator:

windows service

Step 11

Fire the below command in the command prompt and press Enter.

 cd C:\Windows\Microsoft.NET\Framework\v4.0.30319windows service

Step 12

Now Go to your project source folder > bin > Debug and copy the full path of of the Windows Service.exe file

windows service windows service

Step 13 

Open the command prompt and fire the below command and press enter.

Syntax

InstallUtil.exe + Your copied path + \your service name + .exe

Our Path

InstallUtil.exe C:\Users\Faisal-Pathan\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe

windows serviceStep 14

Open services by following the below steps:

  1. Press Window key + R.
  2. Type services.msc
  3. Find your Service.

windows service 

windows service

        

windows service                   

Service Output  

windows service

A log folder will be created in your bin folder. 

If you want to uninstall the service, fire the below command.

  1. Syntax InstallUtil.exe -u + Your copied path + \your service name + .exe
  2. Our path InstallUtil.exe -u C:\Users\Faisal-Pathan\source\repos\MyFirstService\MyFirstService\bin\Debug\MyFirstService.exe

Summary

In this article, we learned how to create a Windows Service and install/uninstall it using the InstallUtil.exe from a command prompt.

I hope that I have explained each step clearly and that it can be easily understood by all developers. You can leave feedback/comments/questions to this article. Please let me know if you like and understand this article and how I could improve it.

I also uploaded this project on GitHub, here.

.NET Microsoft Windows Service Component Architecture Software deployment

Published at DZone with permission of Faisal Pathan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Phased Migration Strategy for Zero Downtime in Systems
  • Feature Flags in .NET 8 and Azure
  • Implementing CRUD Operations With NLP Using Microsoft.Extensions.AI
  • Launching Pega Web Mashup Forms on a Secure Static Website With AWS S3

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!