2008-10-14 156 views
57

如何找到windows service.exe文件的动态安装文件夹?获取Windows服务的完整路径

Path.GetFullPath(relativePath); 

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

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

回答

82

尝试

System.Reflection.Assembly.GetEntryAssembly().Location 
+1

简短而亲切。 :) – 2011-09-26 12:21:00

+3

“System.Reflection.Assembly.GetEntryAssembly()”为我的服务为空。 – 2012-10-29 20:36:42

+2

看看Curtis Yallop答案。好多了! – 2013-07-19 22:34:17

-4

这应该给你的路径的可执行文件位于:

Environment.CurrentDirectory; 

如果没有,你可以尝试:

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

更哈克,但功能方式:

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

:)

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); 

这应该给你的可执行文件的绝对路径。

5

上述的另一种形式:

string path = Assembly.GetExecutingAssembly().Location; 
FileInfo fileInfo = new FileInfo(path); 
string dir = fileInfo.DirectoryName; 
38
Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) 
3

Environment.CurrentDirectory返回其中程序运行当前目录。在Windows服务的情况下,返回可执行文件将运行的位置的%WINDIR%/ system32路径,而不是可执行文件的部署位置。