2

I am trying to set a stream equal to the text content of an embedded resource in my ASP.NET Core project. However, when debugging, the stream is continuously being set to null, and I assume that this is because of the fact that it cannot find this embedded resource to begin with.

I have set the file as an embedded resource by going to Properties > Build Action > Embedded Resource. And then I have also edited the projects .csproj file to include an item group which references the file to include:

<ItemGroup>
  <EmbeddedResource Include="Assets/loyalty-template.html">
    <LogicalName>Assets/Loyalty-template.html</LogicalName>
  </EmbeddedResource>
</ItemGroup>

Where I set the stream:

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

Am I referencing the embedded file correctly in the GetManifestResourceStream? Below is the file structure of my project where loyalty-template.html is situated:

enter image description here

3
  • 3
    Call GetManifestResourceNames to find out if the resource is there and under what name. Commented Oct 10, 2021 at 12:27
  • Isn't it much easier to just set the file as copy to output directory and then File.ReadAllText(Path.Combine("Assets", "loyalty-template.html"));? Commented Oct 10, 2021 at 12:28
  • 1
    It should be {ProjectDefaultNamespace}.Assets.{filename}, i.e. namespace + dot separated path Commented Oct 10, 2021 at 12:42

1 Answer 1

5

Use the following path: [assembly name].[directory].[file name].

OR

Use GetManifestResourceNames with the file name and extension only:

string resourceName = assembly.GetManifestResourceNames()
.Single(str => str.EndsWith("loyalty-template.html")); 
Sign up to request clarification or add additional context in comments.

5 Comments

I have attempted this. However it still cannot find the resource? var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("The-Food-Works-WebAPI.Assets.loyalty-template.html")
This seems to be a fine path. Should be working.
Have you tried the following? string resourceName = assembly.GetManifestResourceNames().Single(str => str.EndsWith("loyalty-template.html"));
Thank you so much. This did the trick. Please update your answer with this comment and ill upvote it!
Thank you @SeventhWarhawk for the upvote! My pleasure to help ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.