C# 編寫windows服務及服務的安裝、啟動、刪除
阿新 • • 發佈:2018-11-16
一、編寫windows服務
1、VS2017 - 建立服務Myservice
2、建立好專案之後 --- >> 雙擊 Service1.cs ---- >> 出現一個設計介面 ---->> 右鍵介面 --- >> 彈出對話方塊選擇 ”新增安裝程式“
3、在設計介面修改 serviceProcessInstaller1的屬性 Account 為 LocalSystem (也可用程式碼修改)
4、在設計介面修改 serviceInstaller1 的屬性: display 為 myfirstservice ; description 為 我的首個服務 ; StartType 為 Automatic
5、修改Service1.cs 程式碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; namespace myservice { public partial class Service1 : ServiceBase {public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { // TODO: 在此處新增程式碼以啟動服務。 System.IO.File.AppendAllText(@"D:\Log.txt", " Service Start :" + DateTime.Now.ToString()); } protectedoverride void OnStop() { // TODO: 在此處新增程式碼以執行停止服務所需的關閉操作。 System.IO.File.AppendAllText(@"D:\Log.txt", " Service Stop :" + DateTime.Now.ToString()); } } }
6、生成解決方案,可以在專案的dubug目錄中找到 myservice.exe
二、SC命令=====安裝、開啟、配置、關閉windows服務
1、將myservice.exe放在英文目錄下,我的是 d:\myservice.exe
2、在cmd中,轉到D:並執行以下使命令進行服務安裝和啟動(這裡的myserv 是自定義的名字)
sc create myserv binPath= "d:/myservice.exe"sc config myserv start= auto //(自動) (DEMAND----手動、DISABLED----禁用) 並且start連著= ,而=的後面有一個空格 net start myserv
可以看到d盤下已生成了log.txt
3.刪除服務,執行以下程式碼
sc delete myserv
4、為方便使用,可編輯為bat批處理檔案
@echo.服務啟動...... @echo off @sc create myserv1 binPath= "d:\demo.exe" @net start myserv1 @sc config myserv1 start= AUTO @echo off @echo.啟動完畢! @pause
5.或在程式中用以下程式碼安裝(參考http://www.cnblogs.com/pingming/p/5115320.html)
//安裝服務 string path = @"D:\demo.exe"; Process.Start("sc", "create myDemo binPath= \"" + path + "\" "); Console.WriteLine("安裝成功"); //解除安裝服務 Process.Start("sc", "delete KJLMDemo"); Console.WriteLine("解除安裝成功"); break;