.Net實現Windows服務安裝完成后自動啟動的兩種方法


考慮到部署方便,我們一般都會將C#寫的Windows服務制作成安裝包。在服務安裝完成以后,第一次還需要手動啟動服務,這樣非常不方便。

方法一:在安裝完成事件里面調用命令行的方式啟動服務

此操作之前要先設置下兩個控件

設置serviceProcessInstaller1控件的Account屬性為“LocalSystem
設置serviceInstaller1控件的StartType屬性為"Automatic"
 
在服務器上添加安裝程序,在private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)事件中,添加以下代碼:
 
[csharp]   view plain copy
  1. /// <summary>  
  2.     /// 安裝后自動啟動服務  
  3.     /// </summary>  
  4.     /// <param name="sender"></param>  
  5.     /// <param name="e"></param>  
  6.     private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)  
  7.     {  
  8.         Process p = new Process  
  9.         {  
  10.             StartInfo =  
  11.             {  
  12.                 FileName = "cmd.exe",  
  13.                 UseShellExecute = false,  
  14.                 RedirectStandardInput = true,  
  15.                 RedirectStandardOutput = true,  
  16.                 RedirectStandardError = true,  
  17.                 CreateNoWindow = true  
  18.             }  
  19.         };  
  20.         p.Start();  
  21.         const string cmdString = "sc start 銀醫通服務平台1.0"//cmd命令,銀醫通服務平台1.0為服務的名稱  
  22.         p.StandardInput.WriteLine(cmdString);  
  23.         p.StandardInput.WriteLine("exit");  
  24.     }  


查閱了網上的一些資料,這種方式雖可行,但覺得不夠完美。好了,下面來看看如何更好地做到服務自動啟動。

方法二:使用ServiceController對象

1.重寫ProjectInstaller的Commit方法

[csharp] view plain copy
  1. using System;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.ComponentModel;  
  5. using System.Configuration.Install;  
  6. using System.Linq;  
  7. using System.ServiceProcess;  
  8. namespace CleanExpiredSessionSeivice  
  9. {  
  10.     [RunInstaller(true)]  
  11.     public partial class ProjectInstaller : System.Configuration.Install.Installer  
  12.     {  
  13.         public ProjectInstaller()  
  14.         {  
  15.             InitializeComponent();  
  16.         }  
  17.   
  18.          public override void Commit(IDictionary savedState)  
  19.         {  
  20.             base.Commit(savedState);  
  21.             ServiceController sc = new ServiceController("銀醫通服務平台1.0");  
  22.             if(sc.Status.Equals(ServiceControllerStatus.Stopped))  
  23.             {  
  24.                 sc.Start();  
  25.             }  
  26.         }  
  27.     }  
  28. }  

2、在服務安裝項目中添加名為 Commit的 Custome Action

在服務安裝項目上右擊,在彈出的菜單中選擇View — Custom Actions

image

 

然后在Commit項上右擊,選擇Add Custom Action…,在彈出的列表框中選擇Application Folder。最終結果如下:

image

 

需要注意的是,第二步操作是必不可少的,否則服務無法自動啟動。我的個人理解是Commit Custom Action 會自動調用ProjectInstaller的Commit方法,Commit Custom Action 在這里扮演了一個調用者的角色。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM