Simple cases of creating, installing, uninstalling, and debugging Windows services in C #

Source: Internet
Author: User

First, create a Windows service

1. To create a Windows service with VS, the results are as follows:

2. Delete the default generated Service1.cs file, and then create your own service file (for example: MyService) and modify the code for the Program.cs file as follows:

At this point, the directory structure for the solution is as follows:

3, double-click the MyService.cs service file, in the left design mode, right click "Add Installer", automatically generate Projectinstaller.cs files and two installation components, as follows:

4, right-click "ServiceProcessInstaller1", select the properties, set account accounts method, recommended for LocalService, as follows:

5. Right-click "ServiceInstaller1", select Properties, set properties

A) The description of the Description service, which is displayed directly to the list of Windows services;

b) DisplayName service display name, directly displayed to the Windows service list name;

c) ServiceName The service process name, the unique identity when installing and uninstalling the service.

As follows:

6, create the Installation Services batch file Install.bat, you can create Notepad, and then modify the suffix to bat, the contents of Notepad are as follows:

%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe WindowsServiceDemo.exe
Net Start MyService
sc config myservice start= auto
Pause

Notepad is saved as a setting that is encoded as ANSI, such as:

7, similarly create the Uninstall service batch file Uninstall.bat, the content is as follows:

%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe/u WindowsServiceDemo.exe
Pause

The directory structure for this solution is as follows:

Second, write the service code

Right-click "MyService.cs" and select View Code as follows:

namespace windowsservicedemo{    Partial class myservice:servicebase    {public        myservice ()        {            InitializeComponent ();        }        protected override void OnStart (string[] args)        {            //TODO: Add code here to start the service.        }        protected override void OnStop ()        {            ///TODO: Add code here to perform the close operation required to stop the service.        }    }}

The following is the implementation of its own simple function, the code is as follows:

Using system;using system.diagnostics;using system.io;using system.serviceprocess;using System.Timers;namespace        windowsservicedemo{Partial class Myservice:servicebase {Private timer time = new timer ();        Public MyService () {InitializeComponent (); } protected override void OnStart (string[] args) {writelog ("service started, Time:" +datetime.now.tostring ("HH:            Mm:ss ") +" \ r \ n "); Time.            Elapsed + = new System.Timers.ElapsedEventHandler (methodevent); Time. Interval = 2 * 1000;//time interval is 2 seconds.        Start (); } protected override void OnStop () {writelog ("service Stopped, Time:" + DateTime.Now.ToString ("HH:mm:ss") + "\        r\n "); } private void Methodevent (object source, System.Timers.ElapsedEventArgs e) {time.            Enabled = false; string result = String.            Empty;            String startTime = DateTime.Now.ToString ("HH:mm:ss");            try {    .... result = "Execution succeeded, Time:" + startTime; } catch (Exception exp) {result = "failed, Reason:" + exp.            Message;                } finally {writelog (result); Time.            Enabled = true; }}///<summary>//logging///</summary>//<param name= "Loginfo" >& lt;/param> public void Writelog (string loginfo) {try {string logdi                Rectory = AppDomain.CurrentDomain.BaseDirectory + "\\Logs"; if (!                Directory.Exists (logdirectory)) {directory.createdirectory (logdirectory);                } string filePath = Logdirectory + "\ \" + DateTime.Now.ToString ("yyyy-mm-dd") + ". txt";            File.appendalltext (FilePath, loginfo); } Catch {}}}}

The function is performed 2 seconds and logs are logged.

Iii. Installing Windows Services

Rebuild the entire solution, after successful, assign the bin file to a custom folder from the folder where the project resides, and copy Install.bat and Uninstall.bat to the Debug folder under Bin.

Run the Install.bat installation service as an administrator with successful results such as:

This is right click on "My Computer", select "Manage", select "Service", you can see the service is installed, such as:

At the same time, the Debug folder has the logs file, the Logs folder contains TXT document, the contents are as follows:

You can see that there is no 2 seconds to execute.

Iv. Uninstalling Windows Services

Uninstall the service, and also run Uninstall.bat as an administrator.

V. Debugging Windows Services

Break point, under "Debugging" in the toolbar, "Attach to Process", attach your own service to debug.

Simple cases of creating, installing, uninstalling, and debugging Windows services in C #

Related Article

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.