Home > Mobile >  How to provide a relative path using System.IO.File inside a hosted ASP.NET Web API?
How to provide a relative path using System.IO.File inside a hosted ASP.NET Web API?

Time:10-12

I have an ASP.NET Web API that is hosted on Azure as an app service. I have workflows that automatically call an endpoint once a month. However, these triggers have been failing due to the following error:

"body": "Could not find a part of the path 'C:\\home\\site\\The-Food-Works-WebAPI\\Assets\\loyalty-template.html'."

At this endpoint, I am attempting to access a file (also in this web api project) through the following code:

string body = System.IO.File.ReadAllText("..\\The-Food-Works-WebAPI\\Assets\\loyalty-template.html");

If I had to run the endpoint locally, everything would work just as intended. I believe the relative path is fine, but due to the way it is being accessed (through System.IO.File), it expects the file to be saved locally?

EDITS: (Using Embedded Resource):

var resourceName = "..//The-Food-Works-WebAPI//Assets//loyalty-template.html";
       string body;
       using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
           {
                TextReader tr = new StreamReader(stream);
                body = tr.ReadToEnd();
           }

Azure now gives the following error:

"body": "Value cannot be null. (Parameter 'stream')"

CodePudding user response:

Thank you @Dai, I am converting the above comments as an answer so that will help other community members:

So after changing your resource name and editing your .csproj to set the <LogicalName> for the resource and then use that for the resourceName and also after disposing the StreamReader instance and by using a using block hopefully resolved the issue.

And It is recommended that always setting an explicit <LogicalName>, otherwise MSBuild generates a resource-name based on the path of the file relative to the .csproj, which means it will change (quite unpredictably so!) if you ever move files around your file-system.

  • Related