2008-10-14 153 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路徑,而不是可執行文件的部署位置。