【问题标题】:Getting full path for Windows Service获取 Windows 服务的完整路径
【发布时间】:2008-10-14 03:49:22
【问题描述】:

如何找到动态安装windows服务.exe文件的文件夹?

Path.GetFullPath(relativePath);

返回基于C:\WINDOWS\system32 目录的路径。

但是,XmlDocument.Load(string filename) 方法似乎对安装服务 .exe 文件的目录内的相对路径起作用。

【问题讨论】:

    标签: c# .net windows-services


    【解决方案1】:

    试试

    System.Reflection.Assembly.GetEntryAssembly().Location
    

    【讨论】:

    • "System.Reflection.Assembly.GetEntryAssembly()" 对于我的服务为空。
    • 看看 Curtis Yallop 的回答。好多了!
    • 返回可执行文件名的路径
    • 使用 AppDomain.CurrentDomain.BaseDirectory - 它不涉及反射。
    【解决方案2】:

    试试这个:

    AppDomain.CurrentDomain.BaseDirectory
    

    (就像这里:How to find windows service exe path

    【讨论】:

    • 谢谢。我有一个 NServiceBus 服务,并且由于它被包裹在 NServiceBus.Host.exe 中,GetEntryAssembly() 在我的实际项目中为空。不过这个效果很好。
    【解决方案3】:
    Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
    

    【讨论】:

      【解决方案4】:

      这适用于我们的 Windows 服务:

      //CommandLine without the first and last two characters
      //Path.GetDirectory seems to have some difficulties with these (special chars maybe?)
      string cmdLine = Environment.CommandLine.Remove(Environment.CommandLine.Length - 2, 2).Remove(0, 1);
      string workDir = Path.GetDirectoryName(cmdLine);  
      

      这应该为您提供可执行文件的绝对路径。

      【讨论】:

        【解决方案5】:

        上述的另一个版本:

        string path = Assembly.GetExecutingAssembly().Location;
        FileInfo fileInfo = new FileInfo(path);
        string dir = fileInfo.DirectoryName;
        

        【讨论】:

          【解决方案6】:

          Environment.CurrentDirectory 返回程序运行的当前目录。如果是 Windows 服务,则返回 %WINDIR%/system32 路径,该路径是可执行文件将运行的位置,而不是可执行文件部署的位置。

          【讨论】:

            【解决方案7】:

            这应该为您提供可执行文件所在的路径:

            Environment.CurrentDirectory;
            

            如果没有,你可以试试:

            Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName
            

            一种更hacky但更实用的方式:

            Path.GetFullPath("a").TrimEnd('a')
            

            :)

            【讨论】:

            • -1:Environment.CurrentDirectory 和你的hacky解决方案都返回当前工作目录,从OP所说的是system32目录。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-03-16
            • 2014-12-14
            • 1970-01-01
            相关资源
            最近更新 更多