天天看點

使用C#建立Windows服務

本文屬于原創,轉載請注明出處,謝謝!

一、開發環境

作業系統:Windows 10 X64

開發環境:VS2015

程式設計語言:C#

.NET版本:.NET Framework 4.0

目标平台:X86

二、建立Windows Service

1、建立一個Windows Service,并将項目名稱改為“MyWindowsService”,如下圖所示:

使用C#建立Windows服務
2、在解決方案資料總管内将Service1.cs改為MyService1.cs後并點選“檢視代碼”圖示按鈕進入代碼編輯器界面,如下圖所示:
使用C#建立Windows服務
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”設計界面,在空白位置右擊滑鼠彈出上下文菜單,選中“添加安裝程式”,如下圖所示:

使用C#建立Windows服務

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

使用C#建立Windows服務

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

使用C#建立Windows服務
使用C#建立Windows服務
使用C#建立Windows服務

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

使用C#建立Windows服務

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

使用C#建立Windows服務

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

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

1、在同一個解決方案裡建立一個Windows Form項目,并命名為WindowsServiceClient,如下圖所示:

使用C#建立Windows服務

2、将該項目設定為啟動項目,并在窗體内添加四個按鈕,分别為安裝服務、啟動服務、停止服務及解除安裝服務,如下圖所示:

使用C#建立Windows服務

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窗體,如下圖所示:

使用C#建立Windows服務

5、由于需要安裝服務,故需要使用UAC中Administrator的權限,滑鼠右擊項目“WindowsServiceClient”,在彈出的上下文菜單中選擇“添加”->“建立項”,在彈出的選擇窗體中選擇“應用程式清單檔案”并單擊确定,如下圖所示:

使用C#建立Windows服務

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

使用C#建立Windows服務

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

使用C#建立Windows服務

8、重新打開後,在IDE運作WindowsServiceClient項目;

9、使用WIN+R的方式打開運作窗體,并在窗體内輸入services.msc後打開服務,如下圖所示:

使用C#建立Windows服務

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

使用C#建立Windows服務

11、點選“運作服務”按鈕,将啟動并運作服務,如下所示:

使用C#建立Windows服務

12、點選“停止服務”按鈕,将會停止運作服務,如下圖所示:

使用C#建立Windows服務

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

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

使用C#建立Windows服務

源代碼下載下傳:

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

補充:如何調試服務

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

使用C#建立Windows服務

2、啟動“WindowsServiceClient”項目,在“調試”菜單中選擇“附件到程序”(服務必須事先安裝),如下所示:

使用C#建立Windows服務

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

使用C#建立Windows服務

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

使用C#建立Windows服務

作者:CNXY

Github:https://www.github.com/cnxy

出處:http://cnxy.me

本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接,否則保留追究法律責任的權利。

如果文中有什麼錯誤,歡迎指出,謝謝!