2011-05-18 116 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