使用 C# 获取可执行文件的绝对路径?
看一下这个伪代码:
string exe_path = system.get_exe_path()
print "This executable is located in " + exe_path
如果我构建上面的程序并将可执行文件放在 C:/meow/
中,它将打印出 Thisexecutable is located in C:/meow/
code> 每次运行时,无论当前工作目录如何。
我如何使用 C#
轻松完成此任务?
Have a look at this pseudocode:
string exe_path = system.get_exe_path()
print "This executable is located in " + exe_path
If I build the above program and place the executable in C:/meow/
, It would print out This executable is located in C:/meow/
each time it is run, regardless of the current working directory.
How could I easily accomplish this using C#
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
MSDN 有一篇文章 说要使用
System.Reflection。 Assembly.GetExecutingAssembly().GetName().CodeBase
;如果您需要该目录,请对该结果使用 System.IO.Path.GetDirectoryName 。或者,有更短的
Application.ExecutablePath
其中“获取启动应用程序的可执行文件的路径,包括可执行文件名称”,因此这可能意味着它的可靠性稍差,具体取决于应用程序的启动方式。MSDN has an article that says to use
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
; if you need the directory, useSystem.IO.Path.GetDirectoryName
on that result.Or, there's the shorter
Application.ExecutablePath
which "Gets the path for the executable file that started the application, including the executable name" so that might mean it's slightly less reliable depending on how the application was launched.我跳入评分最高的答案,却发现自己没有得到我所期望的。我必须阅读评论才能找到我想要的东西。
因此,我发布了评论中列出的答案,以给予其应有的曝光度。
I jumped in for the top rated answer and found myself not getting what I expected. I had to read the comments to find what I was looking for.
For that reason I am posting the answer listed in the comments to give it the exposure it deserves.
“获取包含清单的已加载文件的路径或 UNC 位置。”
请参阅:http://msdn.microsoft.com/en -us/library/system.reflection. assembly.location.aspx
"Gets the path or UNC location of the loaded file that contains the manifest."
See: http://msdn.microsoft.com/en-us/library/system.reflection.assembly.location.aspx
假设我在控制台应用程序中有 .config 文件,现在如下所示。
Suppose i have .config file in console app and now am getting like below.
在我这边,我使用了表单应用程序:
它采用应用程序启动路径。
On my side, I used, with a form application:
it takes the application startup path.
对我有用但不在上面的那个是
Process.GetCurrentProcess().MainModule.FileName
。The one that worked for me and isn't above was
Process.GetCurrentProcess().MainModule.FileName
.如果您计划构建一个与任务计划程序一起使用的控制台应用程序,我建议使用这种方法:
这样,路径将适应您放置可执行文件的任何位置。
If you are planning to build a console application to be used with Task Scheduler, I'd recommend using this approach:
This way, the path will adapt to whatever location you place your executable file in.