C # Creating a Windows service (Windows Services) Basic tutorial

Source: Internet
Author: User

From: http://www.cnblogs.com/sorex/archive/2012/05/16/2502001.html

This piece of Windows service is not complicated, but there are too many things to notice, the online material is also very messy, and occasionally write their own will be absent-minded. So this article is also produced, this article will not write complex things, completely based on the requirements of the application to write, so will not write to the Windows service very deep.

This article describes how to create, install, start, monitor, and uninstall the content steps and considerations for a simple Windows Service in C #.

One, create a Windows service 1) to create a Windows service project

2) Renaming the service

Rename Service1 to your service name, where we are named Servicetest.

Second, create the Service Installer 1) Add Setup program

We can then see that the ProjectInstaller.cs and 2 installed components are created automatically for us.

2) Modify the installation service name

Right-ServiceInsraller1, select Properties, and change the value of ServiceName to servicetest.

3) Modify Installation permissions

Right-ServiceProcessInsraller1, select Properties, and change the account value to LocalSystem.

Third, write service Code 1) Open Servicetest Code

Right-click servicetest and select View Code.

2) Write service logic

Add the following code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Diagnostics; usingSystem.Linq; usingSystem.ServiceProcess; usingSystem.Text;namespaceWindowsServiceTest {     publicpartialclassServiceTest : ServiceBase     {         publicServiceTest()         {             InitializeComponent();         }        protectedoverridevoidOnStart(string[] args)         {             using(System.IO.StreamWriter sw = newSystem.IO.StreamWriter("C:\\log.txt", true))             {                 sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");             }         }        protectedoverridevoidOnStop()         {             using(System.IO.StreamWriter sw = newSystem.IO.StreamWriter("C:\\log.txt", true))             {                 sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop.");             }         }     } }

Here our logic is very simple, start the service to write a log, close the time to write a log.

Iv. Creating the installation script

Add 2 files to the project as follows (must be ANSI or UTF-8 without BOM format ):

1) Installation Script Install.bat
1 2 3 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsServiceTest.exe Net Start ServiceTest sc config ServiceTest start= auto
2) Uninstall Script Uninstall.bat
1 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsServiceTest.exe
3) Installation Script description

The second behavior starts the service.

The third behavior sets the service to run automatically.

These 2 lines are selected on a service basis.

4) Script debugging

If you need to see the script health, add pause to the last line of the script

V. Control of services in C # 0) Configuring the directory structure

CV a new WPF project, called Windowsservicetestui, adds a reference to the system.serviceprocess .

Create the service directory under the Windowsservicetestui bin\debug directory.

Set the build directory for windowsservicetest to the service directory created above.

Post-build directory structure such as

1) Installation

The installation will cause directory problems, so the installation code is as follows:

1 2 3 4 5 6 7 8 stringCurrentDirectory = System.Environment.CurrentDirectory; System.Environment.CurrentDirectory = CurrentDirectory + "\\Service"; Process process = newProcess(); process.StartInfo.UseShellExecute = false; process.StartInfo.FileName = "Install.bat"; process.StartInfo.CreateNoWindow = true; process.Start(); System.Environment.CurrentDirectory = CurrentDirectory;
2) Uninstall

A directory problem also occurs when uninstalling, so the uninstall code is as follows:

1 2 3 4 5 6 7 8 stringCurrentDirectory = System.Environment.CurrentDirectory; System.Environment.CurrentDirectory = CurrentDirectory + "\\Service"; Process process = newProcess(); process.StartInfo.UseShellExecute = false; process.StartInfo.FileName = "Uninstall.bat"; process.StartInfo.CreateNoWindow = true; process.Start(); System.Environment.CurrentDirectory = CurrentDirectory;
3) Start

The code is as follows:

1 2 3) 4 5 using System.ServiceProcess;     ServiceController serviceController = new ServiceController("ServiceTest"); serviceController.Start();
4) Stop
1 2 3 ServiceController serviceController = new ServiceController("ServiceTest"); if (serviceController.CanStop)     serviceController.Stop();
5) Pause/Resume
1 2 3 4 5 6 7 8 ServiceController serviceController = newServiceController("ServiceTest"); if(serviceController.CanPauseAndContinue) {     if(serviceController.Status == ServiceControllerStatus.Running)         serviceController.Pause();     elseif (serviceController.Status == ServiceControllerStatus.Paused)         serviceController.Continue(); }
6) Check the status
1 2 ServiceController serviceController = new ServiceController("ServiceTest"); string Status = serviceController.Status.ToString();
VI. Debug Windows service 1) Install and run the Service 2) attach process

3) Add breakpoints in your code to debug

Vii. Summary

The above configuration for Windows service is not explained in detail in this article, but as described above, you can create a running Windows service that meets the needs of your work.

Sample code See: Https://github.com/sorex/WindowsServiceTest

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.