C#建立Window服務圖解,安裝、配置、以及C#操作Windows服務
阿新 • • 發佈:2018-11-15
一、首先開啟VS2013,建立Windows服務專案
二、建立完成後對"Service1.cs"重新命名位"ServiceDemo";然後切換到程式碼檢視,寫個服務執行日誌。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System. Text;
using System.Threading.Tasks;
namespace KJLMDemo
{
public partial class ServiceDemo : ServiceBase
{
public ServiceDemo()
{
InitializeComponent();
}
//啟動服務
protected override void OnStart(string[] args)
{
WriteLog("服務已開啟:" +DateTime.Now.ToString());
}
//停止服務
protected override void OnStop()
{
WriteLog("服務已關閉:" + DateTime.Now.ToString());
}
//服務暫停執行程式碼
protected override void OnPause()
{
WriteLog("服務暫停:" + DateTime.Now.ToString());
base. OnPause();
}
//服務恢復執行程式碼
protected override void OnContinue()
{
WriteLog("服務恢復:" + DateTime.Now.ToString());
base.OnContinue();
}
//系統即將關閉執行程式碼
protected override void OnShutdown()
{
WriteLog("系統即將關閉:" + DateTime.Now.ToString());
base.OnShutdown();
}
//寫入txt文件,用於除錯日誌
public void WriteLog(string str)
{
using (StreamWriter sw = File.AppendText(@"e:\WindowServerlog.txt"))
{
sw.WriteLine(str);
sw.Flush();
}
}
}
}
三、切換到設計檢視,右鍵點選下圖圈中的“新增安裝程式”
如下圖自動為我們撞見了"ProjectInstaller.cs",以及兩個安裝元件。
四、修改安裝許可權:選中"serviceProcessInstaller1"右鍵屬性;更改Account屬性為LocalSystem
五、修改安裝服務名稱:選中"serviceInstaller1"右鍵屬性;將"ServiceName"的值改為ServiceDemo
六、建立安裝指令碼跳轉到網址:http://www.cnblogs.com/pingming/p/5108947.html(提供三種方法,任何一種都可以)
七、部署Windows服務:
1、將Windows服務執行程式用到的dll等相關檔案放到一個資料夾。
2、把寫好的bat檔案也放進去
注:如果路徑改變,則修改bat檔案裡面的服務執行程式路徑
八、C#通過控制檯操作Windows服務-網址:http://www.cnblogs.com/pingming/p/5115320.html
六、除錯Windows Service
1)安裝並執行服務
2)附加程序
3)在程式碼中加入斷點進行除錯