您现在的位置是: 首页 > .NET CORE > 文章详情 文章详情
【.Net Core】获取绝对路径、相对路径
2019-08-19 【.NET CORE】 2966人浏览
一、绝对路径
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.dll
二、相对路径
从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
很赞哦! (2)
相关文章

热门收藏
- .net core Redis分布式缓存的客户端实现
- .net core API 统一拦截错误
- ASP.NET Core MVC中的IActionFilter.OnActionExecuted方法执行时,Controller中Action返回的对象是否已经输出到Http Response中
- aspnet core 2.1中使用jwt从原理到精通一
- aspnet core 2.1中使用jwt从原理到精通二
- aspnet core 2.1中使用jwt从原理到精通三
- ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统
- 消除 ASP.NET Core 告警 "No XML encryptor configured. Key may be persisted to storage in unencrypted form
- .NET Core 中基于 IHostedService 实现后台定时任务
- 【.Net Core】获取绝对路径、相对路径