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

 

 

 

 

四、调试

五、其他工具

 

posted @ 2019-11-04 18:35  雨水的命运  阅读(2019)  评论(0编辑  收藏  举报