C# Windows服務創建安裝卸載


一、創建Windows服務

 使用VS創建一個新的windows服務應用程序

 

 創建完成之后

 

 

 

 

二、相關配置

修改Service1名稱為StartService(可以不改,自行選擇

 

添加安裝程序並修改配置

 

 

 

 安裝完成之后,源碼中會出現一個ProjectInstaller程序集,雙擊進入頁面修改相關屬性

 

               

 

 

 

    

 

 

 

 添加文件夾和實體類

 

 

 


 LogHelper.cs 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Reflection;
 6 using System.Text;
 7 using System.Threading.Tasks;
 8 
 9 namespace WindowsService.Common
10 {
11     public class LogHelper
12     {
13         /// <summary>
14         /// 獲取程序異常信息
15         /// </summary>
16         /// <param name="methodBase"></param>
17         /// <param name="exception"></param>
18         /// <param name="message"></param>
19         /// <returns></returns>
20         public static string GetExceptionMessage(MethodBase methodBase, Exception exception, string message)
21         {
22             string fullName = methodBase.ReflectedType.FullName;
23             string name = methodBase.Name;
24             string str = $"\r\n異常綜合信息(類:{fullName};函數名稱:{name};):\r\n";
25             str += "-----------\r\n";
26             str += ".Net異常信息:\r\n";
27             if (exception == null)
28             {
29                 str += "   無異常對象,也無堆棧信息(exception == null)\r\n";
30             }
31             else
32             {
33                 str += $"   {exception.Message}\r\n";
34                 str += $".Net堆棧信息:\r\n{exception.StackTrace}\r\n";
35             }
36             str += "-----------\r\n";
37             if (message != null && message.Trim().Length > 0)
38             {
39                 str += "===========\r\n";
40                 str += $"自定義信息:\r\n   {message}\r\n";
41                 str += "===========\r\n";
42             }
43             return str;
44         }
45 
46         /// <summary>
47         /// 寫出日志信息 目錄地址:string logPath = AppDomain.CurrentDomain.BaseDirectory + "00_Log\\";
48         /// </summary>
49         /// <param name="folderName"></param>
50         /// <param name="message"></param>
51         public static void Write(string folderName, string message)
52         {
53             string text = AppDomain.CurrentDomain.BaseDirectory + "00_Log\\";
54             if (folderName != null && folderName.Trim().Length > 0)
55             {
56                 text += folderName;
57             }
58             WritingLogs(text, message);
59         }
60 
61         /// <summary>
62         ///  寫出異常日志(.txt)
63         /// </summary>
64         /// <param name="strPath"></param>
65         /// <param name="strContent"></param>
66         public static void WritingLogs(string strPath, string strContent)
67         {
68             FileStream fileStream = null;
69             StreamWriter streamWriter = null;
70             try
71             {
72                 if (!Directory.Exists(strPath))
73                 {
74                     Directory.CreateDirectory(strPath);
75                 }
76                 strPath = string.Format("{0}\\{1}{2}", strPath, DateTime.Now.ToString("yyyy-MM-dd"), ".txt");
77                 fileStream = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write);
78                 streamWriter = new StreamWriter(fileStream);
79                 streamWriter.BaseStream.Seek(0L, SeekOrigin.End);
80                 streamWriter.WriteLine(strContent + "\r\n\r\n--------------------------------------------------------" + DateTime.Now.ToString() + "--------------------------------------------------------\r\n");
81                 streamWriter.Flush();
82                 streamWriter.Close();
83                 fileStream.Close();
84             }
85             finally
86             {
87                 streamWriter.Close();
88                 fileStream.Close();
89             }
90         }
91 
92 
93     }
94 }
LogHelper

 

 Utility.cs 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace WindowsService.Common
 8 {
 9     public class Utility
10     {
11         /// <summary>
12         /// 是否到時間進行執行
13         /// </summary>
14         /// <param name="hour">當前時間(小時)</param>
15         /// <returns>true:時間已到;false:時間未到;</returns>
16         public static bool TimeOut(string hour)
17         {
18             string times = "14|20|01";
19             if (times == null || times.Trim().Length <= 0)
20             {
21                 return false;
22             }
23             if (times.IndexOf('|') > 0)
24             {
25                 foreach (string t in times.Split('|'))
26                 {
27                     if (t == hour)
28                     {
29                         return true;
30                     }
31                 }
32             }
33             else if (times == hour)
34             {
35                 return true;
36             }
37             return false;
38         }
39     }
40 }
Utility 

 

TaskStart.cs

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Reflection;
 5 using System.ServiceProcess;
 6 using System.Text;
 7 using System.Threading;
 8 using System.Threading.Tasks;
 9 using WindowsService.Common;
10 
11 namespace WindowsService.BusinessServices
12 {
13     public class TaskStart
14     {
15 
16         /// <summary>
17         /// 業務開始運行
18         /// </summary>
19         public void TaskProcessing()
20         {
21             LogHelper.Write("Start", ".....服務正式運行.....");
22             Thread.Sleep(1000 * 20 * 1); //在20秒內進行附加進程
23             try
24             {
25                 bool isRun = false; //默認不執行
26                 while (true)
27                 {
28                     string hour = DateTime.Now.ToString("HH"); //獲得當前的時間
29                     isRun = Utility.TimeOut(hour) ? true : false;
30                     if (isRun)//判斷服務是否運行
31                     {
32                         #region 具體業務
33 
34                         LogHelper.Write("具體業務", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, Guid.NewGuid().ToString()));
35 
36                         #endregion
37 
38 
39                         isRun = false; //已經操作一次
40                         Thread.Sleep(1000 * 60 * 62);   //休眠 62 分鍾  //必須要超過 一個 小時  
41                     }
42                     else
43                     {
44                         //睡眠兩分鍾
45                         Thread.Sleep(1000 * 60 * 2);  //停止設定時間,精確度比Sleep高
46                     }
47                 }
48             }
49             catch (Exception ce)
50             {
51                 LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), ce, "\r\n\r\n.....服務異常.....\r\n\r\n"));
52 
53                 ServiceController service = new ServiceController(new StartService().ServiceName);
54                 service.Stop(); //停止服務
55                 //service.Pause();//暫停服務
56                 //service.Start();//開始服務
57             }
58         }
59     }
60 }
TaskStart(具體業務)

 

 修改啟動服務代碼

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Diagnostics;
 6 using System.Linq;
 7 using System.Reflection;
 8 using System.ServiceProcess;
 9 using System.Text;
10 using System.Threading;
11 using System.Threading.Tasks;
12 using WindowsService.BusinessServices;
13 using WindowsService.Common;
14 
15 namespace WindowsService
16 {
17     public partial class StartService : ServiceBase
18     {
19         /// <summary>
20         /// 當前服務是否停止(默認時flase)
21         /// </summary>
22         private bool isStop = false;
23 
24         /// <summary>
25         /// 啟動服務
26         /// </summary>
27         public StartService()
28         {
29             InitializeComponent();
30 
31             this.CanPauseAndContinue = true;
32             this.CanStop = true;
33             isStop = false;
34         }
35 
36         ///<summary>
37         ///暫停服務
38         ///</summary>
39         protected override void OnPause()
40         {
41             LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....暫停服務.....\r\n\r\n"));
42             isStop = true;  //服務暫停
43         }
44 
45         ///<summary>
46         ///恢復服務
47         ///</summary>
48         protected override void OnContinue()
49         {
50             LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....繼續服務.....\r\n\r\n"));
51             isStop = false; //繼續服務
52         }
53 
54         /// <summary>
55         /// 服務停止
56         /// </summary>
57         protected override void OnStop()
58         {
59             LogHelper.Write("Operation", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), null, "\r\n\r\n.....停止服務.....\r\n\r\n"));
60             isStop = true;  //服務停止
61         }
62 
63         /// <summary>
64         /// 服務開始運行
65         /// </summary>
66         /// <param name="args"></param>
67         protected override void OnStart(string[] args)
68         {
69             try
70             {
71                 //當服務沒有停止時,開始具體業務
72                 if (isStop == false)
73                 {
74                     Thread thread = new Thread(new ThreadStart(new TaskStart().TaskProcessing));
75                     thread.Start();
76                 }
77             }
78             catch (Exception ce)
79             {
80                 LogHelper.Write("Error", LogHelper.GetExceptionMessage(MethodBase.GetCurrentMethod(), ce, "\r\n\r\n.....停止服務.....\r\n\r\n"));
81             }
82         }
83     }
84 }
StartService

 

 

 

 

 

 三、服務安裝

新建一個txt文本,輸入以下內容,這里的WindowsService.exe 是程序路徑,前面的路徑是固定的,后面可變。修改txt文件名稱為bat批處理文件,新建文本文檔.txt——install.bat 。 然后右擊 以管理員身份運行   這個批處理文件。這樣服務就安裝成功了。最后別忘記手動啟動下這個服務。

 

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe  F:\DownLoad\WindowsService\WindowsService\WindowsService\bin\Debug\WindowsService.exe
pause

 

 

 

 

 

 

 

 

 

 

 

、服務卸載

 

 和服務安裝步驟一樣,輸入以下內容。然后 以管理員身份運行 即可。

C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u F:\DownLoad\WindowsService\WindowsService\WindowsService\bin\Debug\WindowsService.exe
pause

 

 

 

 

四、調試

 

 

 

 

源碼地址:https://github.com/RainFate/WindowsServiceDemo/tree/master/WindowsService


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM