一、絕對路徑
1、獲取應用程序運行當前目錄Directory.GetCurrentDirectory()。
System.IO命名空間中存在Directory類,提供了獲取應用程序運行當前目錄的靜態方法GetCurrentDirectory,
但根據.net core的設計,此方法不是真正的獲取應用程序的當前方法,而是執行dotnet命令所在目錄,
var path = Directory.GetCurrentDirectory()
執行結果:
E:\project\24-dingding-saas\Code\DBen.Ding.SaaS.WebMobile
要獲取應用程序運行當前目錄,只能通過變通的方案解決。
如:1、在應用程序的目錄執行dotnet命令,
2、或者通過其他方案。
如下代碼是一種可以獲取應用程序的當前目錄:
dynamic type = (new Program()).GetType(); string currentDirectory = Path.GetDirectoryName(type.Assembly.Location); Console.WriteLine(currentDirectory);
執行結果:
E:\project\24-dingding-saas\Code\DBen.Ding.SaaS.WebMobile\bin\Debug\netcoreapp2.0\DBen.Ding.SaaS.WebMobile.dl
二、相對路徑
從ASP.NET Core RC2開始,可以通過注入 IHostingEnvironment 服務對象來取得Web根目錄和內容根目錄的物理路徑,如下所示:
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);
}
}
}
執行結果:
/Code/DBen.Ding.SaaS.WebMobile/wwwroot /Code/DBen.Ding.SaaS.WebMobile

