我看到有一些方法来获得应用程序文件夹路径:

应用程序。StartupPath System.IO.Path.GetDirectoryName ( System.Reflection.Assembly.GetExecutingAssembly () .Location) AppDomain.CurrentDomain.BaseDirectory System.IO.Directory.GetCurrentDirectory () 环境。CurrentDirectory System.IO.Path.GetDirectoryName ( System.Reflection.Assembly.GetExecutingAssembly () . getname () .CodeBase) System.IO.Path.GetDirectory (Application.ExecutablePath)

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


当前回答

对于web应用程序,要获得当前web应用程序根目录,通常通过web页面调用当前传入的请求:

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

以上代码描述

其他回答

对于web应用程序,要获得当前web应用程序根目录,通常通过web页面调用当前传入的请求:

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

以上代码描述

根据我的经验,最好的方法是两者结合。

.CodeBase System.Reflection.Assembly.GetExecutingAssembly () . getname () 会给你文件夹吗 Directory.GetCurrentDirectory () 在。net Core上可以正常工作,但在。net上不行,会给你项目的根目录 System.AppContext.BaseDirectory和AppDomain.CurrentDomain.BaseDirectory 在。net中运行良好,但不能在。net核心中运行,并将为您提供项目的根目录

在一个类库中。我检查哪个框架托管库,并选择一个或另一个。

获取我使用的简单桌面应用程序的.exe路径

Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)

返回路径到.exe。 还要注意,对于一些域,默认域的.exe将被返回,或者ExecuteAssembly(String)第一次调用时执行的.exe,如果该条目是非托管的,则将返回null。

小心使用GetExecutingAssembly(),命名对我来说是令人困惑的,因为我希望得到。exe,但它返回。dll或。exe,代码放在那里,所以在GetExecutingAssembly()放置在库的情况下,它返回库。

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

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

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

其他选项可能会根据您的环境返回不同的目录—例如,请参阅@Vimvq1987的答案。

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

更新 这些天….NET Core, .NET Standard 1.3+或.NET Framework 4.6+),最好使用AppContext。而不是AppDomain.CurrentDomain.BaseDirectory。两者是等效的,但不再支持多个appdomain。

根目录:

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