Windows服务安装 - 当前目录

时间:2011-05-18 18:42:36

标签: c# windows-services

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

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

将目录设置为

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

这也是初始值。

如何找到正确的道路?

3 个答案:

答案 0 :(得分:9)

试试这个:

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

答案 1 :(得分:3)

您也可以尝试

Assembly.GetExecutingAssembly( ).Location

如果您没有引用winforms或wpf

,这也有效

答案 2 :(得分:1)

我正在进行的项目中遇到了同样的问题,但我们采取了不同的方法。我们不是使用必须与可执行文件位于同一路径的App.config文件,而是更改了安装程序类和服务的主入口点。

我们这样做是因为我们不希望在不同位置使用相同的项目文件。我们的想法是使用相同的分发文件,但使用不同的服务名称。

所以我们做的是在我们的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事件中设置的服务的安装名称。

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

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