C# 获取Windows服务的完整路径

C# 获取Windows服务的完整路径,c#,.net,windows-services,C#,.net,Windows Services,如何找到动态安装windows service.exe文件的文件夹 Path.GetFullPath(relativePath); 返回基于C:\WINDOWS\system32目录的路径 但是,XmlDocument.Load(string filename)方法似乎在使用service.exe文件安装到的目录中的相对路径。试试看 System.Reflection.Assembly.GetEntryAssembly().Location 这将为您提供可执行文件所在的路径: Environ

如何找到动态安装windows service.exe文件的文件夹

Path.GetFullPath(relativePath);
返回基于
C:\WINDOWS\system32
目录的路径

但是,
XmlDocument.Load(string filename)
方法似乎在使用service.exe文件安装到的目录中的相对路径。

试试看

System.Reflection.Assembly.GetEntryAssembly().Location

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

Environment.CurrentDirectory;
如果没有,您可以尝试:

Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName
一种更老套但功能性更强的方式:

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

:)

这适用于我们的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);  

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

上述内容的另一个版本:

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

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

尝试以下操作:

AppDomain.CurrentDomain.BaseDirectory

(就像这里:)

-1:Environment.CurrentDirectory和您的hacky解决方案都返回当前工作目录,OP称之为system32目录。“System.Reflection.Assembly.GetEntryAssembly()”对于我的服务为空。请看Curtis Yallop Answer。好多了!它返回可执行文件名为Use AppDomain.CurrentDomain.BaseDirectory的路径-它不涉及反射。谢谢。我有一个NServiceBus服务,由于它被包装在NServiceBus.Host.exe中,
GetEntryAssembly()
在我的实际项目中为空。不过,这一个工作得很好。
AppDomain.CurrentDomain.BaseDirectory