版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41600552/article/details/83016353
如果要得到传统的ASP.Net应用程序中的相对路径或虚拟路径对应的服务器物理路径,只需要使用使用Server.MapPath()方法来取得Asp.Net根目录的物理路径,如下所示:
// Classic ASP.NET
public class HomeController : Controller
{
public ActionResult Index()
{
string physicalWebRootPath = Server.MapPath("~/");
return Content(physicalWebRootPath);
}
}
但是在ASPNET Core中不存在Server.MapPath()方法,Controller基类也没有Server属性。
在Asp.Net Core中取得物理路径:
从ASP.NET Core RC2开始,可以通过注入 IHostingEnvironment 服务对象来取得Web根目录和内容根目录的物理路径,如下所示:
命名空间引用
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
private readonly IHostingEnvironment _hostingEnvironment;
public QualificationOneualificationController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
获取 路径的写法
string webRootPath = _hostingEnvironment.WebRootPath;
asp.net core应用程序根目录下的wwwroot目录
获取静态目录
string contentRootPath = _hostingEnvironment.ContentRootPath;
Web根目录是指提供静态内容的根目录 就没有 wwwroot
//通过路径再通过IO流判断你所传入的文件在跟目录中是否存在
DirectoryInfo directoryInfo = new DirectoryInfo(webRootPath+"/uploads/images/");
FileInfo foundFileInfo = directoryInfo.GetFiles().Where(x => x.Name ==
fileName).FirstOrDefault();
ASP.NET Core RC1
在ASP.NET Core RC2之前 (就是ASP.NET Core RC1或更低版本),通过 IApplicationEnvironment.ApplicationBasePath 来获取 Asp.Net Core应用程序的根目录(物理路径)
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.PlatformAbstractions; 引用名空间
namespace AspNetCorePathMapping
{
public class HomeController : Controller
{
private readonly IApplicationEnvironment _appEnvironment;
public HomeController(IApplicationEnvironment appEnvironment)
{
_appEnvironment = appEnvironment;
}
public ActionResult Index()
{
return Content(_appEnvironment.ApplicationBasePath);
}
}
}