C#簡單實現建立windows服務
阿新 • • 發佈:2018-12-22
本機環境:win10 64位 vs2017
1.新建WindowsService1
2.在設計頁面單機右鍵->新增安裝程式:
3.右鍵serviceProcessInstaller1,單擊屬性,將Account改為LocalSystem
同樣右鍵serviceInstaller1,單擊屬性,將StartType改為Manual
4.右鍵Service1.cs點選檢視程式碼
5.這裡我們實現開機自啟一個socket服務端。修改程式碼如下 :
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace WindowsService1 { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { //這是我要執行的控制檯程式的路徑,你用的時候換成你的就可以了 string StartAppPath = @"C:\Users\biattt\Desktop\server\server\server\bin\Debug\server.exe"; try { Process proc = new Process(); proc.StartInfo.FileName = StartAppPath; //注意路徑 proc.Start(); } catch (System.Exception ex) { //錯誤處理 //這裡可以打log } //這裡可以打log } protected override void OnStop() { //這裡可以打log } } }
6.生成一下。關閉vs。
7.寫bat指令碼檔案,用於安裝和解除安裝服務。
安裝指令碼Install.bat:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe C:\Users\biattt\Desktop\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe
Net Start Service1
sc config Service1 start= auto
pause
其中第一行前半部分是你電腦安裝服務的installutil.exe程式的地址,後半部分是你安裝的服務的編譯生成的exe檔案地址。
解除安裝指令碼:
net stop WindowsService1
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u C:\Users\biattt\Desktop\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe
/u表示解除安裝。
8.以管理員身份執行Install.bat
9.這是開啟工作管理員看看服務:
10.開啟一個客戶端,顯示連線上了。說明服務真的佈置上了!
11.在管理員身份執行Uninstall.bat。就看到這個服務沒有了。
12.以上,就是 C#簡單實現建立windows服務的過程。