//獲取應用程序所在目錄的2種方式(絕對,不受工作目錄影響,建議采用此方法獲取路徑).
1. string basePath1 = AppContext.BaseDirectory;
例如:E:\\svn項目源碼\\DotNetCore\\1.0\\paralworld\\paralworld.manager.api\\bin\\Debug\\netcoreapp2.2\\netcoreapp2.2\\
2.string basePath2 =Path.GetDirectoryName(typeof(Program).Assembly.Location);
例如:E:\\svn項目源碼\\DotNetCore\\1.0\\paralworld\\paralworld.manager.api\\bin\\Debug\\netcoreapp2.2\\netcoreapp2.2
3.從ASP.NET Core RC2開始,可以通過注入 IHostingEnvironment 服務對象來取得Web根目錄和內容根目錄的物理路徑,如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
using
Microsoft.AspNetCore.Hosting;
using
Microsoft.AspNetCore.Mvc;
namespace
AspNetCorePathMapping
{
public
class
HomeController : Controller
{
private
readonly
IHostingEnvironment _hostingEnvironment;
public
HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public
ActionResult Index()
{
string
webRootPath = _hostingEnvironment.WebRootPath;
string
contentRootPath = _hostingEnvironment.ContentRootPath;
return
Content(webRootPath +
"\n"
+ contentRootPath);
}
}
}
|
例如:webRootPath為E:\\svn項目源碼\\DotNetCore\\1.0\\paralworld\\paralworld.manager.api\\wwwroot\\
contentRootPath為E:\\svn項目源碼\\DotNetCore\\1.0\\paralworld\\paralworld.manager.api
這里要注意區分Web根目錄 和 內容根目錄的區別:
Web根目錄是指提供靜態內容的根目錄,即asp.net core應用程序根目錄下的wwwroot目錄
內容根目錄是指應用程序的根目錄,即asp.net core應用的應用程序根目錄