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

应用程序。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)

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


当前回答

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

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

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

其他回答

这个System.IO.Path.GetDirectory(Application.ExecutablePath)变成了System.IO.Path.GetDirectoryName(Application.ExecutablePath)

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

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

以上代码描述

我成功地用过这个

System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)

它甚至可以在linqpad内部工作。

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

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

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

根目录:

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