Search code examples
asp.net-corepathfilepathpath-combine

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


When I'm running my project in localhost I'm able to locate the file and process it further. This is achieved with this line of code.

path = Path.Combine(Directory.GetCurrentDirectory(), "EmailTemplates\\SuccessOrderWindows10.html");

I'm able to get the full relative path C:\etc\etc\etc.. But when i push this code to production, when it reaches to this stage, it throws an error

Error One or more occurred. (Could not find a part of the path 'h:\root\home\username\www\sitename\EmailTemplates\SuccessOrderWindows10.html'.)

What I'm doing wrong?


Solution

  • Error One or more occurred. (Could not find a part of the path 'h:\root\home\username\www\sitename\EmailTemplates\SuccessOrderWindows10.html'.)

    As the error message said, can't find the file path. On the production environment, please navigate to "h:\root\home\username\www\sitename\EmailTemplates" folder, and check whether it contains the "SuccessOrderWindows10.html' file. If it doesn't contain the related files, it means the file was lost, try to republish the application with all of the files.

    Second, try to use IWebHostEnvironment service ContentRootPath property to get the directory that contains the application content files. Code as below:

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

    The result:

    enter image description here

    More detail information about using IWebHostEnvironment, you could check this article:

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