获取应用程序文件夹路径的最佳方法
我看到有一些方法可以获取应用程序文件夹路径:
I see that there are some ways to get the application folder path:
Application.StartupPath
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
AppDomain.CurrentDomain.BaseDirectory
System.IO.Directory.GetCurrentDirectory()
Environment.CurrentDirectory
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
System.IO.Path.GetDirectory(Application.ExecutablePath)
视情况而定,最好的方法是什么?
What is the best way depending on the situation?
AppDomain.CurrentDomain.BaseDirectory
可能对于访问位置相对于应用程序安装目录的文件最有用.
AppDomain.CurrentDomain.BaseDirectory
is probably the most useful for accessing files whose location is relative to the application install directory.
在 ASP.NET 应用程序中,这将是应用程序根目录,而不是 bin 子文件夹 - 这可能是您通常想要的.在客户端应用程序中,它将是包含主要可执行文件的目录.
In an ASP.NET application, this will be the application root directory, not the bin subfolder - which is probably what you usually want. In a client application, it will be the directory containing the main executable.
在 VSTO 2005 应用程序中,它将是包含应用程序的 VSTO 托管程序集的目录,而不是 Excel 可执行文件的路径.
In a VSTO 2005 application, it will be the directory containing the VSTO managed assemblies for your application, not, say, the path to the Excel executable.
其他人可能会根据您的环境返回不同的目录 - 例如,请参阅 @Vimvq1987 的回答.
The others may return different directories depending on your environment - for example see @Vimvq1987's answer.
CodeBase
是找到文件的地方,可以是一个以 http://开头的 URL.在这种情况下,Location
可能是程序集下载缓存.不保证为 GAC 中的程序集设置 CodeBase.
CodeBase
is the place where a file was found and can be a URL beginning with http://. In which case Location
will probably be the assembly download cache. CodeBase is not guaranteed to be set for assemblies in the GAC.
更新现在(.NET Core、.NET Standard 1.3+ 或 .NET Framework 4.6+)最好使用 AppContext.BaseDirectory
而不是 AppDomain.CurrentDomain.BaseDirectory
.两者都是等价的,但不再支持 多个 AppDomains.
UPDATE
These days (.NET Core, .NET Standard 1.3+ or .NET Framework 4.6+) it's better to use AppContext.BaseDirectory
rather than AppDomain.CurrentDomain.BaseDirectory
. Both are equivalent, but multiple AppDomains are no longer supported.