//获取应用程序所在目录的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应用的应用程序根目录