在生产中尝试通过 .net core 3.X 中的相对路径读取文件时出错

Error when trying to read a file via relative path in .net core 3.X in production

当我 运行 我在本地主机上的项目时,我能够找到文件并进一步处理它。这是通过这行代码实现的。

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'.)

我做错了什么?

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”文件,如果不包含相关文件,则说明文件丢失, 尝试使用所有文件重新发布应用程序。

其次,尝试使用IWebHostEnvironment service ContentRootPath property获取包含应用程序内容文件的目录。代码如下:

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();
    }

结果:

更多关于使用IWebHostEnvironment的详细信息,您可以查看这篇文章:

Getting the Web Root Path and the Content Root Path in ASP.NET Core