获取Windows服务的完整路径

Sam*_*Kim 58 .net c# windows-services

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

Path.GetFullPath(relativePath);
Run Code Online (Sandbox Code Playgroud)

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

但是,该XmlDocument.Load(string filename)方法似乎是针对安装服务.exe文件的目录中的相对路径.

Gre*_*ean 83

尝试

System.Reflection.Assembly.GetEntryAssembly().Location
Run Code Online (Sandbox Code Playgroud)

  • 对于我的服务,"System.Reflection.Assembly.GetEntryAssembly()"为null. (3认同)
  • 看看Curtis Yallop的回答者.好多了! (2认同)

Cur*_*lop 66

试试这个:

AppDomain.CurrentDomain.BaseDirectory
Run Code Online (Sandbox Code Playgroud)

(就像这里:如何找到Windows服务exe路径)

  • 谢谢你。我有一个 NServiceBus 服务,因为它被包裹在 NServiceBus.Host.exe 中,所以在我的实际项目中`GetEntryAssembly()` 为空。不过,这个工作得很好。 (2认同)

小智 38

Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
Run Code Online (Sandbox Code Playgroud)


low*_*der 5

这适用于我们的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);  
Run Code Online (Sandbox Code Playgroud)

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


Chr*_*s S 5

上面的另一个版本:

string path = Assembly.GetExecutingAssembly().Location;
FileInfo fileInfo = new FileInfo(path);
string dir = fileInfo.DirectoryName;
Run Code Online (Sandbox Code Playgroud)