Asp.net core 在生产环境中尝试通过.net core 3.X中的相对路径读取文件时出错
当我在localhost中运行我的项目时,我能够找到文件并进一步处理它。这是通过这行代码实现的Asp.net core 在生产环境中尝试通过.net core 3.X中的相对路径读取文件时出错,asp.net-core,path,filepath,path-combine,Asp.net Core,Path,Filepath,Path Combine,当我在localhost中运行我的项目时,我能够找到文件并进一步处理它。这是通过这行代码实现的 path=path.Combine(Directory.GetCurrentDirectory(),“EmailTemplates\\SuccessOrderWindows10.html”); 我能够得到完整的相对路径C:\etc\etc\etc。。但是当我把这段代码推到生产阶段,当它达到这个阶段时,它抛出了一个错误 Error One or more occurred. (Could not fi
path=path.Combine(Directory.GetCurrentDirectory(),“EmailTemplates\\SuccessOrderWindows10.html”);
我能够得到完整的相对路径C:\etc\etc\etc。。但是当我把这段代码推到生产阶段,当它达到这个阶段时,它抛出了一个错误
Error One or more occurred. (Could not find a part of the path 'h:\root\home\username\www\sitename\EmailTemplates\SuccessOrderWindows10.html'.)
我做错了什么
出现一个或多个错误。(找不到路径的一部分
“h:\root\home\username\www\sitename\EmailTemplates\SuccessOrderWindows10.html”。)
正如错误消息所说,找不到文件路径。在生产环境中,请导航到“h:\root\home\username\www\sitename\EmailTemplates”文件夹,并检查它是否包含“SuccessOrderWindows10.html”文件。如果它不包含相关文件,则表示该文件已丢失,请尝试使用所有文件重新发布应用程序
其次,尝试使用获取包含应用程序内容文件的目录。代码如下:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IWebHostEnvironment _hostEnvironment;
public HomeController(ILogger<HomeController> logger, IWebHostEnvironment environment)
{
_logger = logger;
_hostEnvironment = environment;
}
public IActionResult Index()
{
ViewData["WebRootPath"] = Path.Combine(_hostEnvironment.WebRootPath, "Files\\Image1.PNG");
ViewData["ContentRootPath"] = Path.Combine(_hostEnvironment.ContentRootPath, "Files\\Image1.PNG");
//ViewData["Directorypath"] = Path.Combine(Directory.GetCurrentDirectory(), "Files\\Image1.PNG");
return View();
}
公共类HomeController:控制器
{
专用只读ILogger\u记录器;
私人只读IWebHostEnvironment\u hostEnvironment;
公共家庭控制器(ILogger记录器、IWebHostEnvironment环境)
{
_记录器=记录器;
_招待环境=环境;
}
公共IActionResult索引()
{
ViewData[“WebRootPath”]=Path.Combine(_hostenEnvironment.WebRootPath,“Files\\Image1.PNG”);
ViewData[“ContentRootPath”]=Path.Combine(_hostenEnvironment.ContentRootPath,“Files\\Image1.PNG”);
//ViewData[“Directorypath”]=Path.Combine(Directory.GetCurrentDirectory(),“Files\\Image1.PNG”);
返回视图();
}
结果是:
有关使用IWebHostEnvironment的更多详细信息,您可以查看本文: