C# Windows Service 用代碼實現安裝、運行和卸載服務的方法

来源:https://www.cnblogs.com/qingcaodi/archive/2020/06/10/13084289.html
-Advertisement-
Play Games

網上很多創建Widows Service 的方法,其安裝和運行服務的方式大多是通過cmd 命令來實現的,這裡將通過控制台的形式實現安裝、運行和卸載服務。 主頁代碼: 1 using KQService.Job; 2 using KQService.Utils; 3 using System; 4 u ...


網上很多創建Widows Service 的方法,其安裝和運行服務的方式大多是通過cmd 命令來實現的,這裡將通過控制台的形式實現安裝、運行和卸載服務。

主頁代碼:

  1 using KQService.Job;
  2 using KQService.Utils;
  3 using System;
  4 using System.Collections.Generic;
  5 using System.Configuration;
  6 using System.Linq;
  7 using System.ServiceProcess;
  8 using System.Text;
  9 using System.Threading.Tasks;
 10 
 11 namespace KQService.WS
 12 {
 13     static class Program
 14     {
 15         static string ServiceName = ConfigurationManager.AppSettings["ServiceName"];
 16         /// <summary>
 17         /// 應用程式的主入口點。
 18         /// </summary>
 19         static void Main(string[] args)
 20         {
 21             //帶參啟動運行服務
 22             if (args.Length > 0)
 23                 try
 24             {
 25                 ServiceBase[] serviceToRun = new ServiceBase[] { new ServiceInit() };
 26                 ServiceBase.Run(serviceToRun);
 27             }
 28             catch (Exception ex)
 29             {
 30                 LogHelper.Error("服務異常:\r\n" + ex.Message + "\r\n" + ex.InnerException);
 31             }
 32 
 33 
 34             //不帶參啟動配置程式   
 35              else
 36             {
 37                 ServiceInstallWindow();
 38             }
 39 
 40             Console.ReadKey();
 41         }
 42         /// <summary>
 43         /// 啟動安裝服務界面
 44         /// </summary>
 45         static void ServiceInstallWindow()
 46         {
 47             while (true)
 48             {
 49                 Console.WriteLine("請選擇你要執行的操作:");
 50                 Console.WriteLine("1運行服務");
 51                 Console.WriteLine("2停止服務");
 52                 Console.WriteLine("3安裝服務");
 53                 Console.WriteLine("4卸載服務");
 54                 Console.WriteLine("5驗證服務狀態");
 55                 Console.WriteLine("6退出");
 56                 Console.WriteLine("————————————————————");
 57 
 58                 char keyChar = Console.ReadKey().KeyChar;
 59 
 60                 //運行服務
 61                 if (keyChar == '1')
 62                 {
 63                     Console.WriteLine("\r\n服務已啟動,請稍後......");
 64                     if (ServiceHelper.IsServiceExisted(ServiceName))
 65                     {
 66                         ServiceHelper.StartService(ServiceName);
 67                         Console.WriteLine("\r\n服務已啟動!");
 68                     }
 69                     else
 70                     {
 71                         Console.WriteLine("\r\n服務不存在......");
 72                     }
 73                 }
 74                 //停止服務
 75                 if (keyChar == '2')
 76                 {
 77                     Console.WriteLine("\r\n服務正在停止,請稍後......");
 78                     if (ServiceHelper.IsServiceExisted(ServiceName))
 79                     {
 80                         ServiceHelper.StopService(ServiceName);
 81                         Console.WriteLine("\r\n服務已停止!");
 82                     }
 83                     else
 84                     {
 85                         Console.WriteLine("\r\n服務不存在......");
 86                     }
 87                 }
 88                 //安裝服務
 89                 else if (keyChar == '3')
 90                 {
 91                     if (!ServiceHelper.IsServiceExisted(ServiceName))
 92                     {
 93                         ServiceHelper.ConfigService(ServiceName, true);
 94                     }
 95                     else
 96                     {
 97                         Console.WriteLine("\r\n服務已存在......");
 98                     }
 99                 }
100                 //卸載服務
101                 else if (keyChar == '4')
102                 {
103                     if (ServiceHelper.IsServiceExisted(ServiceName))
104                     {
105                         ServiceHelper.ConfigService(ServiceName, false);
106                     }
107                     else
108                     {
109                         Console.WriteLine("\r\n服務不存在......");
110                     }
111                 }
112                 //驗證服務
113                 else if (keyChar == '5')
114                 {
115                     if (!ServiceHelper.IsServiceExisted(ServiceName))
116                     {
117                         Console.WriteLine("\r\n服務不存在......");
118                     }
119                     else
120                     {
121                         Console.WriteLine("\r\n服務狀態:" + ServiceHelper.GetServiceStatus(ServiceName).ToString());
122                     }
123                 }
124                 //退出
125                 else if (keyChar == '6')
126                 {
127                     break;
128                 }
129                 else
130                 {
131                     Console.WriteLine("\r\n請輸入一個有效鍵!");
132                     Console.WriteLine("————————————————————");
133                 }
134             }
135         }
136     }
137 }
ServiceHelper 代碼:
using System;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.ServiceProcess;
using System.Configuration.Install;

namespace RabbitMQClientService.Common
{
    public class ServiceHelper
    {
        #region 服務是否存在
        /// <summary>
        /// 服務是否存在
        /// </summary>
        /// <param name="serviceName">服務名</param>
        /// <returns></returns>
        public static bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region 啟動服務
        /// <summary>
        /// 啟動服務
        /// </summary>
        /// <param name="serviceName">服務名</param>
        public static void StartService(string serviceName)
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                //判斷服務狀態
                if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending)
                {
                    try
                    {
                        service.Start(); //啟動服務
                        for (int i = 0; i < 60; i++)
                        {
                            service.Refresh();
                            Thread.Sleep(1000);
                            if (service.Status == ServiceControllerStatus.StartPending || service.Status == ServiceControllerStatus.Running) //判斷服務是否正常運行
                            {
                                break;
                            }
                            if (i == 59)
                            {
                                LogHelper.WriteErrorLog("啟動服務失敗:" + serviceName, null);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteErrorLog("啟動服務失敗:" + ex.Message, ex);
                    }
                    
                }
            }
        }
        #endregion

        #region 停止服務
        /// <summary>
        /// 停止服務
        /// </summary>
        /// <param name="serviceName">服務名</param>
        public static void StopService(string serviceName)
        {
            using (ServiceController service = new ServiceController(serviceName))
            {
                //判斷服務狀態
                if (service.Status == ServiceControllerStatus.StartPending || service.Status == ServiceControllerStatus.Running)
                {
                    try
                    {
                        if (service.CanStop)
                        {
                            // 如果許可權不夠是不能Stop()的。
                            service.Stop();
                            // 這句話如果沒有對該服務的後續操作可以不要,C#程式只是以許可權向操作系統發出關閉某服務的消息而已,真正關閉該服務的是操作系統而非此C#程式(下麵的Start的也一樣)
                            service.WaitForStatus(ServiceControllerStatus.Stopped);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteErrorLog("停止服務失敗: \r\n" + ex.Message, ex);
                    }
                }
            }

        }
        #endregion

        #region 獲取服務狀態
        /// <summary>
        /// 獲取服務狀態
        /// </summary>
        /// <param name="serviceName">服務名</param>
        /// <returns></returns>
        public static ServiceControllerStatus GetServiceStatus(string serviceName)
        {
            ServiceController service = new ServiceController(serviceName);
            return service.Status;
        }
        #endregion

        #region 配置服務(安裝和卸載)
        /// <summary>
        /// 配置服務(安裝和卸載)
        /// </summary>
        /// <param name="serviceName">服務名</param>
        /// <param name="install">是否安裝,true安裝,false 卸載</param>
        public static void ConfigService(string serviceName, bool install)
        {
            TransactedInstaller ti = new TransactedInstaller();
            ti.Installers.Add(new ServiceProcessInstaller
            {
                Account = ServiceAccount.LocalSystem
            });
            ti.Installers.Add(new ServiceInstaller
            {
                DisplayName = serviceName,
                ServiceName = serviceName,
                Description = "考勤數據同步",
                StartType = ServiceStartMode.Automatic//運行方式
            });
            ti.Context = new InstallContext();
            ti.Context.Parameters["assemblypath"] = "\"" + Assembly.GetEntryAssembly().Location + "\" /service";
            if (install) //是否安裝服務
            {
                ti.Install(new Hashtable());
            }
            else
            {
                ti.Uninstall(null);
            }
        }
        #endregion
    }
}

該方法主要引用了 System.ServiceProcess.ServiceController 類,

界面效果如下:

 

 

 

 

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • ——有時轉換函數更搭配友元函數、有時多餘的轉換函數會幹擾友元函數的運行 Stonewt operator + (const Stonewt &st1, cosnt Stonewt &st2) { double pds = st1.pounds + st2.pounds; Stonewt sum(pd ...
  • 1、首先引入摩爾定律: 每18個月所享受的電子產品價值會翻倍,這一理論在1972年提出,說是經過了前面50年的實際驗證, 後又更改為每兩年所享受的電子產品價值會翻倍,但是隨著時代的發展,目前的摩爾定律時間越來越長,每兩年實現翻倍,越來越不現實, 以後電腦可能要往量子電腦方向進行發展,那個時候可能 ...
  • super()是調用父類的構造函數,並且在當前的那個構造函數的第一行。當super被調用時,他將會第一時間去調用父類的構造函數。 this()是調用本類的另一個構造函數,構造方法一般有無參和帶參兩種 , 它和super一樣也是只能放在第一行,也就是說super()和this()不能同時出現在一個構造 ...
  • 前言 本文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯繫我們以作處理。 作者:碼里奧編程 加企鵝群695185429即可免費獲取,資料全在群文件里。資料可以領取包括不限於Python實戰演練、PDF電子文檔、面試集錦、學習資料等 效果圖 最終效果 ...
  • 作者:美圖博客 https://www.meitubk.com/zatan/386.html 前言 最近突然有個奇妙的想法,就是當我對著電腦屏幕的時候,電腦會先識別屏幕上的人臉是否是本人,如果識別是本人的話需要回答電腦說的暗語,答對了才會解鎖並且有三次機會。如果都沒答對就會發送郵件給我,通知有人在動 ...
  • 前言 已經好多年都沒有使用 SVN 了,它的一些使用套路現在也忘記得差不多了,最近由於手賤給其中一個分支加鎖了,等解鎖的時候忘記怎麼解開了,類似下麵的樣子: 自己挖的坑還是自己來填吧,這裡簡單記錄一下。 解決方案 如果項目加鎖了,我們可以查看到當前鎖的狀態,如下圖所示: 如果想對單個文件解鎖,只需要 ...
  • Volo.Abp.MailKit封裝繼承MailKit庫,為Abp郵件發送提供了快捷實現。 郵箱配置 qq郵箱支持smtp功能,需要去申請開通。參考qq郵箱設置,最重要的是smtp發送郵件,qq郵箱對應的密碼不是用戶的qq郵箱密碼,而是需要申請生成的授權碼。 在項目的appsettings.json ...
  • 什麼是網關 簡單點說網關是一個Api伺服器,是系統的唯一入口。為每個客戶端提供一個定製的Restful API。同時它還需要具有一些業務之外的責任:鑒權。靜態響應等處理。 為什麼需要gateway 我們知道我們要進入一個服務本身,並不是一件容易的事情。服務本身有自己的通訊協議,這種協議往往不能很好的 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...