1. 程式人生 > 實用技巧 >C# 建立windows服務 並通過winform 程式控制服務的 安裝 啟動 停止 解除安裝

C# 建立windows服務 並通過winform 程式控制服務的 安裝 啟動 停止 解除安裝

一、開發環境

作業系統:Windows 10 X64

開發環境:VS2015

程式語言:C#

.NET版本:.NET Framework 4.5

目標平臺:X86

二、建立Windows Service

1、新建一個Windows Service,並將專案名稱改為“MyWindowsService”,如下圖所示:

2、在解決方案資源管理器內將Service1.cs改為MyService1.cs後並點選“檢視程式碼”圖示按鈕進入程式碼編輯器介面,如下圖所示:

3、在程式碼編輯器內如入以下程式碼,如下所示:

using System;
using System.ServiceProcess;
using System.IO;

namespace MyWindowsService
{
    public partial class MyService : ServiceBase
    {
        public MyService()
        {
            InitializeComponent();
        }

        string filePath = @"D:\MyServiceLog.txt";

        protected override void OnStart(string[] args)
        {
            using (FileStream stream = new FileStream(filePath,FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服務啟動!");
            }
        }

        protected override void OnStop()
        {
            using (FileStream stream = new FileStream(filePath, FileMode.Append))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.WriteLine($"{DateTime.Now},服務停止!");
            }
        }
    }
}

4、雙擊專案“MyWindowsService”進入“MyService”設計介面,在空白位置右擊滑鼠彈出上下文選單,選中“新增安裝程式”,如下圖所示:

5、此時軟體會生成兩個元件,分別為“serviceInstaller1”及“serviceProcessInstaller1”,如下圖所示:

6、點選“serviceInstaller1”,在“屬性”窗體將ServiceName改為MyService,Description改為我的服務,StartType保持為Manual,如下圖所示:

7、點選“serviceProcessInstaller1”,在“屬性”窗體將Account改為LocalSystem(服務屬性系統級別),如下圖所示:

8、滑鼠右鍵點選專案“MyWindowsService”,在彈出的上下文選單中選擇“生成”按鈕,如下圖所示:

9、至此,Windows服務已經建立完畢。

三、建立安裝、啟動、停止、解除安裝服務的Windows窗體

1、在同一個解決方案裡新建一個Windows Form專案,並命名為WindowsServiceClient,如下圖所示:

2、將該專案設定為啟動專案,並在窗體內新增四個按鈕,分別為安裝服務、啟動服務、停止服務及解除安裝服務,如下圖所示:

3、按下F7進入程式碼編輯介面,引用“System.ServiceProcess”及“System.Configuration.Install”,並輸入如下程式碼:

using System;
using System.Collections;
using System.Windows.Forms;
using System.ServiceProcess;
using System.Configuration.Install;

namespace WindowsServiceClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe";
        string serviceName = "MyService";

        //事件:安裝服務
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName)) this.UninstallService(serviceName);
            this.InstallService(serviceFilePath);
        }

        //事件:啟動服務
        private void button2_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName)) this.ServiceStart(serviceName);
        }

        //事件:停止服務
        private void button4_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
        }

        //事件:解除安裝服務
        private void button3_Click(object sender, EventArgs e)
        {
            if (this.IsServiceExisted(serviceName))
            {
                this.ServiceStop(serviceName);
                this.UninstallService(serviceFilePath);
            }
        }

        //判斷服務是否存在
        private bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController sc in services)
            {
                if (sc.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        //安裝服務
        private void InstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                IDictionary savedState = new Hashtable();
                installer.Install(savedState);
                installer.Commit(savedState);
            }
        }

        //解除安裝服務
        private void UninstallService(string serviceFilePath)
        {
            using (AssemblyInstaller installer = new AssemblyInstaller())
            {
                installer.UseNewContext = true;
                installer.Path = serviceFilePath;
                installer.Uninstall(null);
            }
        }
        //啟動服務
        private void ServiceStart(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Stopped)
                {
                    control.Start();
                }
            }
        }

        //停止服務
        private void ServiceStop(string serviceName)
        {
            using (ServiceController control = new ServiceController(serviceName))
            {
                if (control.Status == ServiceControllerStatus.Running)
                {
                    control.Stop();
                }
            }
        }
    }
}

4、為了後續除錯服務及安裝解除安裝服務的需要,將已生成的MyWindowsService.exe引用到本Windows窗體,如下圖所示:

5、由於需要安裝服務,故需要使用UAC中Administrator的許可權,滑鼠右擊專案“WindowsServiceClient”,在彈出的上下文選單中選擇“新增”->“新建項”,在彈出的選擇窗體中選擇“應用程式清單檔案”並單擊確定,如下圖所示:

6、開啟該檔案,並將<requestedExecutionLevel level="asInvoker" uiAccess="false" />改為<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />,如下圖所示:

7、IDE啟動後,將會彈出如下所示的窗體(有的系統因UAC配置有可能不顯示),需要用管理員許可權開啟:

8、重新開啟後,在IDE執行WindowsServiceClient專案;

9、使用WIN+R的方式開啟執行窗體,並在窗體內輸入services.msc後開啟服務,如下圖所示:

10、點選窗體內的“安裝服務”按鈕,將會在服務中出現MyService,如下圖所示:

11、點選“執行服務”按鈕,將啟動並執行服務,如下所示:

12、點選“停止服務”按鈕,將會停止執行服務,如下圖所示:

13、點選“解除安裝服務”按鈕,將會從服務中刪除MyService服務。

14、以上啟動及停止服務將會寫入D:\MyServiceLog.txt,內容如下所示:

原始碼下載:

http://pan.baidu.com/s/1kVza3Bp

補充:如何除錯服務


1、要除錯服務,其實很簡單,如需將服務附加程序到需要除錯的專案裡面即可,假如要除錯剛才建的服務,現在OnStop事件裡設定斷點,如下所示:



2、啟動“WindowsServiceClient”專案,在“除錯”選單中選擇“附件到程序”(服務必須事先安裝),如下所示:



3、找到“MyWindowsService.exe”,點選“附加”按鈕,如下圖所示:



4、點選“停止服務”按鈕,程式將會在設定斷點的地方中斷,如下圖所示:





=
======================================================= 華麗的分割線 第二種方式 =======================================================



namespace WindowsService1
{
    public partial class MyService : ServiceBase
    {
        public MyService()
        {
            InitializeComponent();
        }

        string filePath = @"D:\MyServiceLog.txt";

        protected override void OnStart(string[] args)
        {
            using (FileStream stream = new FileStream(filePath,FileMode.Append))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine($"{DateTime.Now},服務啟動!");
                    for (int i = 0; i < 20; i++)
                    {
                        Thread.Sleep(1000);
                        writer.WriteLine("當前內容: "+ i );
                    }
                }
            }
        }

        protected override void OnStop()
        {
            using (FileStream stream = new FileStream(filePath,FileMode.Append))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine($"{DateTime.Now},服務停止");
                }
            }
        }
    }
}



使用bat釋出方式
bat內容
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319\
InstallUtil.exe 

InstallUtil D:\WindowsService1\bin\Debug\WindowsService1.exe   //服務專案地址
Net Start Service1
pause

其中C:\Windows\Microsoft.NET\Framework\v4.0.30319\為installutil的路徑

WindowsServiceTest.exe為Windows Service服務的應用程式,教程

Service1為服務名

ps:.bat與WindowsService1.exe在同一路徑

執行結果:

正在執行事務處理安裝。

正在開始安裝的“安裝”階段。
檢視日誌檔案的內容以獲得 D:\WindowsService1\bin\Debug\WindowsService1.exe 程式集的進度。
該檔案位於 D:\WindowsService1\bin\Debug\WindowsService1.InstallLog。
正在安裝程式集“D:\WindowsService1\bin\Debug\WindowsService1.exe”。
受影響的引數是:
   logtoconsole =
   logfile = D:\WindowsService1\bin\Debug\WindowsService1.InstallLog
   assemblypath = D:\WindowsService1\bin\Debug\WindowsService1.exe
正在安裝服務 MyService...
正在日誌 Application 中建立 EventLog 源 MyService...

在“安裝”階段發生異常。
System.Security.SecurityException: 未找到源,但未能搜尋某些或全部事件日誌。  不可訪問的日誌: Security。

正在開始安裝的“回退”階段。
檢視日誌檔案的內容以獲得 D:\WindowsService1\bin\Debug\WindowsService1.exe 程式集的進度。
該檔案位於 D:\WindowsService1\bin\Debug\WindowsService1.InstallLog。
正在回滾程式集“D:\WindowsService1\bin\Debug\WindowsService1.exe”。
受影響的引數是:
   logtoconsole =
   logfile = D:\WindowsService1\bin\Debug\WindowsService1.InstallLog
   assemblypath = D:\WindowsService1\bin\Debug\WindowsService1.exe
正在將事件日誌還原到源 MyService 的前一狀態。
在 System.Diagnostics.EventLogInstaller 安裝程式的“回退”階段發生異常。
System.Security.SecurityException: 未找到源,但未能搜尋某些或全部事件日誌。  不可訪問的日誌: Security。
在安裝的“回退”階段發生異常。將忽略該異常並繼續回退。但是,在完成回退後計算機可能無法完全還原到它的初始狀態。

“回退”階段已成功完成。

已完成事務處理安裝。
安裝失敗,已執行回退。

很明顯了,是許可權問題。

【解決方案】

右鍵管理員許可權開啟.bat檔案


刪除:

解除安裝很簡單,開啟cmd, 直接輸入 sc deleteWindowsService1 便可(要以管理員身份執行)否則結果如下


參考:https://www.cnblogs.com/cncc/p/7170951.html