2010-02-12 46 views
45

我正在嘗試使用VisualStudio.Net部署項目安裝C#windows服務項目。安裝Windows服務時的憑證

運行部署的項目,我單擊鼠標右鍵,然後從上下文菜單中選擇「安裝」,安裝嚮導運行,並最終促使我一個「設置服務登錄」對話框,詢問用戶名密碼&。

當我從命令行使用sc實用程序安裝服務時,我不必提供憑據。

我必須爲此服務創建登錄嗎?與其他服務一樣,我更願意使用「本地系統」或「網絡服務」(不確定區別是什麼)。

回答

80

將此代碼添加到您在Windows服務項目中的projectInstaller.Designer.cs文件中的私人無效InitializeComponent()方法中。

this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; 

如果你定義的安裝過程是:

private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; 
+1

這就是我所需要的。謝謝! – Keith

+0

不客氣:) – anthares

+0

@anthares我需要以當前用戶身份運行該服務,我該如何解決該問題?我使用:ServiceAccount。用戶但在安裝時獲取密碼請求... – Zhenya

4

在包含的服務項目中,添加一個安裝程序類。使它看起來是這樣的:

[RunInstaller(true)] 
public class MyServiceInstaller : Installer 
{ 
    public MyServiceInstaller() 
    { 
     ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller(); 
     serviceProcessInstaller.Account = ServiceAccount.LocalSystem; // Or whatever account you want 

     var serviceInstaller = new ServiceInstaller 
     { 
      DisplayName = "Insert the display name here", 
      StartType = ServiceStartMode.Automatic, // Or whatever startup type you want 
      Description = "Insert a description for your service here", 
      ServiceName = "Insert the service name here" 
     }; 

     Installers.Add(_serviceProcessInstaller); 
     Installers.Add(serviceInstaller); 
    } 

    public override void Commit(IDictionary savedState) 
    { 
     base.Commit(savedState); 

     // This will automatically start your service upon completion of the installation. 
     try 
     { 
      var serviceController = new ServiceController("Insert the service name here"); 
      serviceController.Start(); 
     } 
     catch 
     { 
      MessageBox.Show(
       "Insert a message stating that the service couldn't be started, and that the user will have to do it manually"); 
     } 
    } 
} 

然後,在Solution Explorer中,部署項目單擊鼠標右鍵,選擇「查看>自定義操作」。右鍵單擊「自定義操作」,然後選擇「添加自定義操作...」選擇「應用程序文件夾」並選擇包含該服務的項目的主要輸出。現在,自定義操作(上面的Commit)將在安裝後執行。如果您需要其他自定義操作,則可以添加其他方法(InstallRollback,Uninstall)。

+0

我不明白嗎?這將如何幫助他,將系統帳戶設置爲執行服務? – anthares

+0

這就是我從我的項目中複製代碼所得到的結果。 {facepalm}在我的項目安裝程序的'Install'方法中,我設置了'Account'屬性。它現在已經修復... – fre0n

+0

偉大的信息。謝謝! – Keith

14

檢查此鏈接:http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx

注意這部分:要爲您的服務創建安裝

修改您的ServiceProcessInstaller:

在設計上,單擊ServiceProcessInstaller1爲Visual Basic項目或serviceProcessInstaller1用於Visual C#項目。將帳戶屬性設置爲LocalSystem。這將導致服務被安裝並在本地服務帳戶上運行。

+1

這優先於通過projectInstaller.Designer.cs文件中的代碼進行設置。 – Jerther