如何找到windows service.exe文件的動態安裝文件夾?獲取Windows服務的完整路徑
Path.GetFullPath(relativePath);
返回基於C:\WINDOWS\system32
目錄的路徑。
但是,XmlDocument.Load(string filename)
方法似乎在服務.exe文件安裝到的目錄內的相對路徑工作。
如何找到windows service.exe文件的動態安裝文件夾?獲取Windows服務的完整路徑
Path.GetFullPath(relativePath);
返回基於C:\WINDOWS\system32
目錄的路徑。
但是,XmlDocument.Load(string filename)
方法似乎在服務.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;
Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
Environment.CurrentDirectory返回其中程序運行當前目錄。在Windows服務的情況下,返回可執行文件將運行的位置的%WINDIR%/ system32路徑,而不是可執行文件的部署位置。
簡短而親切。 :) – 2011-09-26 12:21:00
「System.Reflection.Assembly.GetEntryAssembly()」爲我的服務爲空。 – 2012-10-29 20:36:42
看看Curtis Yallop答案。好多了! – 2013-07-19 22:34:17