获取我的.exe文件的路径

265

我该如何获取我的.exe文件路径?因为如果我复制我的.exe文件,我就可以得到新的路径?

4个回答

339
System.Reflection.Assembly.GetEntryAssembly().Location;

167
我只想要路径,但我发现这个命令给了我路径和可执行文件的文件名。 :-( 另一方面,GetEntryAssembly().Location会给出带有"file://"的路径 - 我需要的是AppDomain.CurrentDomain.BaseDirectory - user799821
22
这在单元测试项目中不起作用。GetEntryAssembly()为空。 - Eric J.
14
System.Reflection.Assembly.GetExecutingAssembly().Location返回当前执行程序集所在的位置,但该位置可能与未执行时的程序集所在位置不同。对于影子复制程序集,会返回临时目录中的路径。System.Reflection.Assembly.GetExecutingAssembly().CodeBase将返回程序集的“永久”路径。 - Cyrus
10
只需使用 Path.GetDirectoryName 即可获取不包含文件名的文件夹路径。 - ProfK
12
谢谢,这正是我需要的。完整解决方案对我有用:System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase) - SnookerC
显示剩余4条评论

178

此外:

AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location

第一个是您应用程序可执行文件的目录。注意!它可以在运行时更改。

第二个是您从中运行代码的程序集(.dll)的目录。


31
AppDomain.CurrentDomain.BaseDirectory在一个单元测试项目中可用。 - Eric J.
6
Assembly.GetEntryAssembly().Location对我来说有效。第一个有file;\,而第二个提供了执行.exe文件的绝对路径。添加System.IO.Path.GetDirectoryName()可仅获取路径。 - CraftedGaming

79
在一个Windows窗体项目中:
获取完整路径(包括文件名):string exePath = Application.ExecutablePath;
获取只有路径的部分:string appPath = Application.StartupPath;

13
如果在.exe快捷方式中设置了"工作目录",或者进程是从另一个应用程序启动的,那么Application.StartupPath将会受到影响。 - Pedro77

4

在Visual Studio 2008中,您可以使用以下代码:

   var _assembly = System.Reflection.Assembly
               .GetExecutingAssembly().GetName().CodeBase;

   var _path = System.IO.Path.GetDirectoryName(_assembly) ;

4
这并不是完全正确的答案。它会给你一个像“file://foo”的字符串。 - dyatchenko
同时,在 System.IO.Path.GetDirectoryName 中也会出现 ArgumentException。 - benderto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接