如何找到动态安装 Windows 服务 .exe 文件的文件夹?
Path.GetFullPath(relativePath);
返回基于C:\WINDOWS\system32
目录的路径。
但是,该XmlDocument.Load(string filename)
方法似乎对安装服务 .exe 文件的目录中的相对路径起作用。
如何找到动态安装 Windows 服务 .exe 文件的文件夹?
Path.GetFullPath(relativePath);
返回基于C:\WINDOWS\system32
目录的路径。
但是,该XmlDocument.Load(string filename)
方法似乎对安装服务 .exe 文件的目录中的相对路径起作用。
尝试
System.Reflection.Assembly.GetEntryAssembly().Location
Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
这适用于我们的 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 路径,该路径是可执行文件将运行的位置,而不是可执行文件部署的位置。
这应该为您提供可执行文件所在的路径:
Environment.CurrentDirectory;
如果没有,您可以尝试:
Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName
一种更hacky但更实用的方式:
Path.GetFullPath("a").TrimEnd('a')
:)