lss
lss

Reputation: 1325

Azure static files System.IO.DirectoryNotFoundException

I have an ASP.NET Core application running on Azure. The application sends various emails - both in plaintext and HTML formats. I have created a subfolder in our Resources folder, called EmailTemplates, where I store all the HTML and TXT templates. An example path could be:

\src\WebProject\Resources\EmailTemplates\Welcome.html

I access the file in my EmailService.cs class in the following manner:

var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Resources", "EmailTemplates", "Welcome.html");
var htmlTemplate = await File.ReadAllTextAsync(filePath);

This works great when running on local environment both on IIS and Kestrel. However, when deployed to Azure, I get an IO error message:

System.IO.DirectoryNotFoundException
An unhandled exception has occurred: Could not find a part of the path 'D:\home\site\wwwroot\Resources\EmailTemplates\Welcome.html'.

I have found a similar question on StackOverflow, but the answer is almost 6 years old. I am not sure, whether it still applies since Azure has changed significantly in the past couple of years. I was also looking at official documentation (1) (2), but I did not find anything special about Azure.

What is the correct way to store and retrieve email templates (and other static files) in ASP.NET Core and Azure?

Upvotes: 7

Views: 7450

Answers (3)

A. Morel
A. Morel

Reputation: 10344

No matter where the files are in the project, if you make your files "Embedded ressource" and "Copy if newer" in the property, when publish, folder and files will be created !

enter image description here

Upvotes: 0

Lee Liu
Lee Liu

Reputation: 2091

When we publish our .Net Core web app to azure, all of its contents are placed under this path [D:\home\site\wwwroot] except static files.

According to your description, we need to create the Resources folder under wwwroot in our project. Then we can access the file using below code after we publish to azure:

var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Resources", "EmailTemplates", "Welcome.html");

We can look over the directory information of our project in azure via KUDU: Using KUDU with Microsoft Azure Web Apps

Update:

We need to allow our Resources folder would be copied to publish directory at csproj file as below:

<Content Include="Resource\*">
  <CopyToPublishDirectory>always</CopyToPublishDirectory>
</Content>

enter image description here

Upvotes: 1

astaykov
astaykov

Reputation: 30903

Make sure your static files are part of your project.

And mark them explicitly as content and Copy to output folder -> always.

Upvotes: 8

Related Questions