C# 获取 Windows 服务的完整路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/199961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting full path for Windows Service
提问by Samuel Kim
How can I find out the folder where the windows service .exe file is installed dynamically?
如何找到动态安装windows服务.exe文件的文件夹?
Path.GetFullPath(relativePath);
returns a path based on C:\WINDOWS\system32
directory.
返回基于C:\WINDOWS\system32
目录的路径。
However, the XmlDocument.Load(string filename)
method appears to be working against relative path inside the directory where the service .exe file is installed to.
但是,该XmlDocument.Load(string filename)
方法似乎适用于安装服务 .exe 文件的目录中的相对路径。
采纳答案by Greg Dean
Try
尝试
System.Reflection.Assembly.GetEntryAssembly().Location
回答by TheSoftwareJedi
This should give you the path that the executable resides in:
这应该为您提供可执行文件所在的路径:
Environment.CurrentDirectory;
If not, you could try:
如果没有,您可以尝试:
Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName
A more hacky, but functional way:
一种更hacky但实用的方式:
Path.GetFullPath("a").TrimEnd('a')
:)
:)
回答by lowglider
This works for our windows service:
这适用于我们的 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);
This should give you the absolute path of the executable.
这应该为您提供可执行文件的绝对路径。
回答by Chris S
Another version of the above:
上面的另一个版本:
string path = Assembly.GetExecutingAssembly().Location;
FileInfo fileInfo = new FileInfo(path);
string dir = fileInfo.DirectoryName;
回答by Chris S
Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)
回答by Amzath
Environment.CurrentDirectory returns current directory where program is running. In case of windows service, returns %WINDIR%/system32 path that is where executable will run rather than where executable deployed.
Environment.CurrentDirectory 返回程序运行的当前目录。对于 Windows 服务,返回 %WINDIR%/system32 路径,该路径是可执行文件将运行的位置,而不是可执行文件部署的位置。
回答by Curtis Yallop
Try this:
尝试这个:
AppDomain.CurrentDomain.BaseDirectory
(Just like here: How to find windows service exe path)
(就像这里:如何找到 Windows 服务 exe 路径)