59

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

Path.GetFullPath(relativePath);

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

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

4

7 回答 7

84

尝试

System.Reflection.Assembly.GetEntryAssembly().Location
于 2008-10-14T03:57:51.667 回答
70

试试这个:

AppDomain.CurrentDomain.BaseDirectory

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

于 2012-10-29T20:48:57.000 回答
39
Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
于 2008-11-14T14:54:26.680 回答
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);  

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

于 2008-10-14T13:38:32.433 回答
5

上面的另一个版本:

string path = Assembly.GetExecutingAssembly().Location;
FileInfo fileInfo = new FileInfo(path);
string dir = fileInfo.DirectoryName;
于 2008-10-14T14:24:16.583 回答
3

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

于 2010-06-11T20:57:57.017 回答
-4

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

Environment.CurrentDirectory;

如果没有,您可以尝试:

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

一种更hacky但更实用的方式:

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

:)

于 2008-10-14T04:06:52.697 回答