【问题标题】:Windows Service installation - current directoryWindows 服务安装 - 当前目录
【发布时间】:2011-05-19 03:19:21
【问题描述】:

这个问题与我的 previous one 有关。我用 C# 编写了一个服务,我需要让它的名称动态并从配置文件中加载名称。问题是调用服务安装程序时的当前目录是 net framework 4 目录,而不是我的程序集所在的目录。

使用该行(这有助于解决同样的问题,但在服务已经运行时) System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

将目录设置为

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

这也是初始值。

如何获得正确的路径?

【问题讨论】:

  • 此页面上的解决方案对我来说不太适用。我可以获得正确的目录,但调用 SetCurrentDirectory 后配置值仍然只是空字符串。之后您是否做了其他事情来导致 .config 文件被加载?
  • 帮可怜的肖恩有点晚了,但我找到了解决方案here直接打开配置文件。

标签: c# windows-services


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    你也可以试试

    Assembly.GetExecutingAssembly( ).Location
    

    如果您不引用 winforms 或 wpf,这也有效

    【讨论】:

      【解决方案3】:

      在我正在进行的一个项目中,我们遇到了同样的问题,但我们采用了不同的方法。我们没有使用必须与可执行文件位于同一路径的 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 事件中设置的服务的安装名称。

      这种方法存在一些问题,例如:

      • 我们必须为不带参数安装的服务创建一个默认名称。例如,如果没有将名称传递给我们的服务,那么我们使用默认名称;
      • 您可以将传递给我们应用程序的服务名称更改为与已安装的不同。

      【讨论】:

      • 感谢您的回答。这是一个不错的解决方案,但是我现在没有安装程序,需要快速部署多个服务,所以我更喜欢第一个想法。
      猜你喜欢
      • 2012-05-09
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 2011-09-15
      • 2017-03-12
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多