Reference Static Files in Blazor Server Side When on Published Host

Viewed 274

On Blazor Server, How to I access a file in a directory when published to the web (hosted) net5.0. I have a folder named Templates that I need to merge a cshtlm file with. For example, this works locally but when published, it fails "Could not find file". If it is not in the www folder do I need to use a controller? Newbee starting to learn.

   public async Task SendEmailAsync()
{

    string contentRootPath = Environment.ContentRootPath;
    var templateDir = Path.Combine(contentRootPath, @"Templates") ;
    var templateFilePath = Path.Combine(templateDir, "CleanDeskPolicy.cshtml");

    try
    {
        var vm = new NewAccountVm()
        {
            Username = "John Doe",
            Message = "Thank you for signing up with us!"
        };

        await EmailFactory.Create()
            .To("XXXXXX@gmail.com")
            .Subject("New Account")
            **.UsingTemplateFromFile(templateFilePath, vm)**
            .SendAsync();

        _logs.Add($"{DateTime.Now}: Email notification was sent successfully ✔!");
    }
    catch (Exception ex)
    {
        _logs.Add($"{DateTime.Now}: Failed to send email notification ❌! ({ex.Message})");
    }
}
2 Answers

You need to put your files in the wwwroot folder

I use IWebHostEnvironment to get the filepath for my files - this works both locally and in my published app. My templates folder is inside wwwroot. In properties for each template file, I set the Built Action as "Content".

 public class MailService : IMailService
    {
        private readonly MailSettings _mailSettings;
    private readonly IWebHostEnvironment _webHostEnvironment;
    public MailService(IOptions<MailSettings> mailSettings, IWebHostEnvironment webHostEnvironment)
    {
        _mailSettings = mailSettings.Value;
        _webHostEnvironment = webHostEnvironment;
    }

    public async Task SendResetPasswordEmailAsync(MailRequest mailRequest, string callBackURL)
    {
        string FilePath = _webHostEnvironment.WebRootPath + "\\templates\\ResetPassword.html";
        StreamReader str = new StreamReader(FilePath);
        string MailText = str.ReadToEnd();
        str.Close();
Related