使用C#建立Windows服務

來源:互聯網
上載者:User

標籤:一個   設定斷點   htable   names   one   ted   pre   get   單擊   

一、開發環境

作業系統:Windows 10 X64

開發環境:VS2015

程式設計語言:C#

.NET版本:.NET Framework 4.0

目標平台: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,內容如下所示:

 

補充:如何調試服務

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

 

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

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

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

 

轉載自:http://www.cnblogs.com/cncc/p/7170951.html

使用C#建立Windows服務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.