Search code examples
c#asp.net-coreembedded-resource

Cannot access embedded resource in ASP.NET Core C# project?


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


Solution

  • 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"));