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

标签 c# .net

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

  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)

根据情况,最好的方法是什么?

最佳答案

AppDomain.CurrentDomain.BaseDirectory 可能最适合用于访问其位置相对于应用程序安装目录的文件。

在 ASP.NET 应用程序中,这将是应用程序根目录,而不是 bin 子文件夹 - 这可能是您通常需要的。在客户端应用程序中,它将是包含主要可执行文件的目录。

在 VSTO 2005 应用程序中,它将是包含应用程序的 VSTO 托管程序集的目录,而不是 Excel 可执行文件的路径。

其他人可能会根据您的环境返回不同的目录 - 例如请参阅@Vimvq1987 的回答。

CodeBase 是找到文件的地方,可以是以 http://开头的 URL。在这种情况下,Location 可能是程序集下载缓存。不保证为 GAC 中的程序集设置代码库.

更新 如今(.NET Core、.NET Standard 1.3+ 或 .NET Framework 4.6+)最好使用 AppContext.BaseDirectory 而不是 AppDomain.CurrentDomain.BaseDirectory。两者是等价的,但是 multiple AppDomains are no longer supported .

关于c# - 获取应用程序文件夹路径的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6041332/

相关文章:

c# - EntityFramework 存储库从接口(interface)和抽象类 : how to use dependency inject on ASP. NET MVC 驱动

c# - 如何从 Expression<Func<MyClass, string>> 动态创建 Expression<Func<MyClass, bool>> 谓词?

c# - Azure AD B2C - URL 错误

c# - 使用 .NET 在 Windows XP 中刻录 DVD 所需的基本 COM 组件是什么?

.net - 使用 System.Data.OracleClient 时如何指定要使用的 Oracle Home

c# - .NET 通用方法问题

.net - RazorEngine - 命名空间导入编译错误

c# - mscorlib.dll 中发生“System.StackOverflowException”?

.net - azure 管道,依赖性检查(.net)

c# - 刷新DataGridView?