自己做网站打开是乱码,招标建设网站,广东网站建设找,开网店详细步骤以下是C#获取不同类型项目根目录的实现方法汇总#xff0c;以及在 .NET Core 中获取项目根目录的方法#xff1a;
控制台应用程序
string rootPath Environment.CurrentDirectory;
string rootPath AppDomain.CurrentDomain.BaseDirectory;
string rootPath Path.GetFul…以下是C#获取不同类型项目根目录的实现方法汇总以及在 .NET Core 中获取项目根目录的方法
控制台应用程序
string rootPath Environment.CurrentDirectory;
string rootPath AppDomain.CurrentDomain.BaseDirectory;
string rootPath Path.GetFullPath(../../);WinForm应用程序
string rootPath Application.StartupPath;
string rootPath Directory.GetCurrentDirectory();
string rootPath AppDomain.CurrentDomain.BaseDirectory;MVC和WebForm项目
string rootPath Server.MapPath(/);Web API项目
string rootPath System.Web.Hosting.HostingEnvironment.MapPath(/);
string rootPath HttpRuntime.AppDomainAppPath;在 .NET Core 中可以使用以下方法获取项目的根目录
使用 AppContext.BaseDirectory 属性
可以使用 AppContext.BaseDirectory 属性获取应用程序的根目录例如
string rootPath AppContext.BaseDirectory;使用 Directory.GetCurrentDirectory() 方法
可以使用 Directory.GetCurrentDirectory() 方法获取当前工作目录例如
string rootPath Directory.GetCurrentDirectory();需要注意的是在某些情况下当前工作目录可能不是应用程序的根目录。
使用 IWebHostEnvironment.ContentRootPath 属性ASP.NET Core
在 ASP.NET Core 应用程序中可以使用 IWebHostEnvironment.ContentRootPath 属性获取应用程序的根目录例如
string rootPath _hostEnvironment.ContentRootPath;需要注意的是要使用该方法需要在应用程序中注入 IWebHostEnvironment 接口。
使用 AppContext.BaseDirectory 和 System.Reflection.Assembly.GetEntryAssembly().Location 属性
可以使用 AppContext.BaseDirectory 和 System.Reflection.Assembly.GetEntryAssembly().Location 属性获取应用程序的根目录例如
string rootPath Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);需要注意的是System.Reflection.Assembly.GetEntryAssembly() 方法在某些情况下可能返回 null因此该方法的可靠性可能不如其他方法。
需要注意的是以上方法获取的是应用程序的根目录而不是项目的根目录。在某些情况下应用程序的根目录可能与项目的根目录不同。