获取应用程序文件夹路径的最佳方法

668

我看到有几种方法可以获取应用程序文件夹路径:

  1. Application.StartupPath
  2. System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location)
  3. AppDomain.CurrentDomain.BaseDirectory
  4. System.IO.Directory.GetCurrentDirectory()
  5. Environment.CurrentDirectory
  6. System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
  7. System.IO.Path.GetDirectory(Application.ExecutablePath)

根据不同情况,哪种方法是最好的呢?


11
为什么我们有很多种方法来获取应用程序路径?我认为每种方法都有其原因。 - Leo Vo
1
#6 中有一个错误:应该是 System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase, System.IO.Path.GetDirectoryName(Application.ExecutablePath)。 - BillW
2
太好了,我在一个网站项目中。但是我不想在我的IoC加载库(它与Web无关)中使用Server.MapPath逻辑。 - bkwdesign
1
我们现在拥有可靠的IHostEnvironment.ContentRootPath,通过注入的IHostEnvironment依赖项进行访问(其中包含其他有用的内容)。 - Timo
1
还有Process.GetCurrentProcess().MainModule.FileName - nawfal
2
#4和#5是不正确的。它们返回当前目录,而不是应用程序所在的目录。(它们有时相同,但这只是一个巧合。) - ikegami
11个回答

-1

根目录:

DriveInfo cDrive = new DriveInfo(System.Environment.CurrentDirectory);
var driverPath = cDrive.RootDirectory;

1
这似乎是获取当前工作目录,虽然有时可能很有用,但绝对不能保证是EXE路径。 - krowe2

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