简体   繁体   中英

Hosted asp.net application DirectoryNotFoundException

I have an application running on my local server. The application runs locally without any error. But, when I host the application in the Heroku . It produces the error as:

DirectoryNotFoundException: Could not find a part of the path'/app/heroku_output/EmailTemplate/EmailConfirm.html'.

I have been trying to read the file using the below code:

private const string templatePath = @"EmailTemplate/{0}.html";

private string GetEmailBody(string templateName)
{
    var body = File.ReadAllText(string.Format(templatePath, templateName));
    return body;
}

The folder EmailTemplate is in my root directory as shown in the figure.

在此处输入图像描述

That folder has also been uploaded to Github and hosted properly in the Heroku. But the application is looking at the file in the wrong project directory ie in (/app/heroku_output).

What am I missing in my code? How do I approach to read those directories?

After looking for all the deployed files,

You attempt to read a file. Reading files is possible within the wwwroot folder. So move your templates there. To access the wwwroot folder use the WebRootPath property from object injected as IWebHostEnvironment

public class EmailTemplateGenerator
{
    private IWebHostEnvironment _env;
    public EmailTemplateGenerator(IWebHostEnvironment env)
    {
        _env = env;
    }

    public void GetEmailBody(string templateName)
    {
        var template = File.OpenRead(Path.Combine(_env.WebRootPath, $"EmailTemplate/{templateName}.html")
    }
}

Try following:

In Visual Studio

If you are using Visual Studio to publish, right click each of those files under "EmailTemplate" folder and select "Properties" and set value of "Copy to Output Directory" to "Copy Always". This will make Visual Studio to publish these files to hosted environment. If you are using different application to publish files just make sure "EmailTemplate" folder is published to hosted environment.

In Code

To be on the safe side always access your files through base URL. Example is given below.

//private const string templatePath = @"EmailTemplate/{0}.html";
private const string templatePath = @"EmailTemplate\\{0}.html";

private string GetEmailBody(string templateName)
{
    //var body = File.ReadAllText(string.Format(templatePath, templateName));
    string baseURL = AppDomain.CurrentDomain.BaseDirectory;
    var body = File.ReadAllText(string.Format(baseURL + "\\" + templatePath, templateName));
    return body;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM