ASP.NET Core (.csproj) Embedded Resources

ASP.NET Core MVC Embedded ResourcesI’ve previously blogged about how to have embedded resources in ASP.NET Core, however that was with the older project.json.  I figured I would show how the project.json translates to the new csproj format.  If you are using Visual Studio 2017, the process via UI should feel pretty standard.

If you have any questions with this post, please let me know in the comments or on Twitter.

 

Visual Studio 2017

For my example, I’ve included a json file called fake.json I pulled from Mockaroo.  Here’s a screenshot of VS2017 that shows the Data/fakedata.json file in my solution.

Solution

If you right click on the fakedata.json, and go to Properties, you will be presented with a familiar properties dialog.  This is where you can set the Build Action to Embedded Resource

File Properties Dialog

.csproj

If you prefer to edit the .csproj file by hand or are using another IDE/editor, you simply have to add two new ItemGroup‘s.

Make sure the path to your files are relative to your csproj.  Here’s a full copy of my solution.

GetManifestResourceStream

Now in your code, you can access the Assembly API to get our your embedded resource.

Note that GetManifestResourceStream takes a string that represents your file.  The path would be the assembly name and the folder structure is used as a namespace.

Also  in the above code, the entry assembly (EntryAssembly.csproj/dll) is being used.  If you’re embedded resource is in another assembly, you will need to use different reflection code to get that assembly.

Questions

The source for this demo is available on GitHub.

If you have any questions regarding embedded resources or converting from project.json, I’d love to hear from you.  Please leave a comment or on twitter.