我看到有一些方法可以获取应用程序文件夹路径:
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)
根据情况,最好的方法是什么?
最佳答案
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/