2011-05-18 94 views
0

此問題與我的previous one有關。我用C#編寫了一個服務,我需要使其名稱爲動態,並從配置文件加載名稱。問題是服務安裝程序被調用時的當前目錄是網絡框架4目錄,而不是我的程序集所在的目錄。Windows服務安裝 - 當前目錄

使用該行(這有助於解決同一問題,但服務已在運行) System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

設置目錄

C:\Windows\Microsoft.NET\Framework\v4.0.30319 

這也是初始值。

如何找到正確的道路?

+0

本頁面的解決方案對我來說並不完全適用。我可以得到正確的目錄,但在調用SetCurrentDirectory之後,配置值仍然只是空字符串。你有沒有做別的事情導致.config文件被加載後? – Sean 2013-07-15 18:58:50

回答

7

試試這個:

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); 
3

您也可以嘗試

Assembly.GetExecutingAssembly().Location 

這也適用,如果你不引用的WinForms或WPF

1

我們在一個項目中有同樣的問題我正在努力,但我們採取了不同的方法。我們不是使用必須與可執行文件位於同一路徑中的App.config文件,而是更改了安裝程序類和服務的Main入口點。

我們這樣做是因爲我們不希望在不同位置使用相同的項目文件。這個想法是使用相同的分發文件,但使用不同的服務名稱。

所以我們所做的就是我們的ProjectInstaller內:

private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e) 
    { 
     string keyPath = @"SYSTEM\CurrentControlSet\Services\" + this.serviceInstaller1.ServiceName; 
     RegistryKey ckey = Registry.LocalMachine.OpenSubKey(keyPath, true); 
     // Pass the service name as a parameter to the service executable 
     if (ckey != null && ckey.GetValue("ImagePath")!= null) 
      ckey.SetValue("ImagePath", (string)ckey.GetValue("ImagePath") + " " + this.serviceInstaller1.ServiceName); 
    } 

    private void ProjectInstaller_BeforeInstall(object sender, InstallEventArgs e) 
    { 
     // Configura ServiceName e DisplayName 
     if (!String.IsNullOrEmpty(this.Context.Parameters["ServiceName"])) 
     { 
      this.serviceInstaller1.ServiceName = this.Context.Parameters["ServiceName"]; 
      this.serviceInstaller1.DisplayName = this.Context.Parameters["ServiceName"]; 
     } 
    } 

    private void ProjectInstaller_BeforeUninstall(object sender, InstallEventArgs e) 
    { 
     if (!String.IsNullOrEmpty(this.Context.Parameters["ServiceName"])) 
      this.serviceInstaller1.ServiceName = this.Context.Parameters["ServiceName"]; 
    } 

我們使用InstallUtil來安設我們這樣的服務:

[FramerokPath]\installutil /ServiceName=[name] [ExeServicePath]

然後,你的應用程序的Main切入點內,我們檢查了args屬性以獲取我們在AfterInstall事件中設置的服務的安裝名稱。

這種方法有一些問題,如:

  • 我們不得不爲沒有參數安裝服務創建一個默認名稱。例如,如果沒有名稱傳遞給我們的服務,那麼我們使用默認的名稱;
  • 您可以將傳遞給我們的應用程序的服務名稱更改爲與安裝的名稱不同。
+0

感謝您的回答。這是一個很好的解決方案,但我現在沒有安裝程序,需要快速部署多個服務,所以我寧願選擇第一個想法。 – kubal5003 2011-05-18 19:26:07