windows服務開發
阿新 • • 發佈:2018-03-16
操作 installer .bat 分享圖片 send 手動安裝 net orm ide
學然後知不足 教然後知困。
沒做過windows service開發時,感覺很難,無從下手。再網看了些例子,加上自己的理解,寫下開發步驟。
開發步驟
新建windows service
添加服務,發表後將再自己的電腦的 服務管理 查看到
partial class MyService : ServiceBase { Timer timer1; public MyService() { InitializeComponent(); } protected override void OnStart(string[] args) { // TODO: Add code here to start your service. using (StreamWriter sw = File.AppendText(@"D:\\log2.txt")) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Start."); } timer1 = new Timer(); timer1.Interval = 2000; timer1.Elapsed += (sender, e) => { using (StreamWriter sw = File.AppendText(@"D:\\log2.txt")) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Countue..."); } }; timer1.Start(); } protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to stop your service. using (StreamWriter sw = File.AppendText(@"D:\\log2.txt")) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Stop."); } } }
- 添加服務安裝程序(這是vs給提供的方便操作),可以發表多個服務。
右擊,點擊Add Installer
,自動生成類ProjectInstaller
。大家可以看下vs自動生成的類ProjectInstaller.Designer.cs
文件
private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); //設置服務安裝信息 this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; //要安裝的服務(保證與你的服務名一致,可添加多個) this.serviceInstaller1.ServiceName = "MyService"; //服務加入 this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.serviceProcessInstaller1, this.serviceInstaller1}); }
註意將服務安裝設置為:手動安裝
服務安裝卸載腳本
Install.bat 文件:%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe "%~dp0%WindowsServiceTest.exe" pause
Uninstall.bat文件:
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe -u "%~dp0%WindowsServiceTest.exe" pause
windows服務開發