I’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.
Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
Visual Studio 2017For 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.jsonfile in my 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
.csprojIf 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.
GetManifestResourceStreamNow in your code, you can access the Assembly API to get our your embedded resource. Note that
GetManifestResourceStreamtakes 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.
4 thoughts to “ASP.NET Core (.csproj) Embedded Resources”
Nice, didn’t see the Assembly.GetEntryAssembly() method. That’s better. Thanks.
I hope you don’t mind the question here, but it seems related.
*crickets* Found a work around.
Sorry, didn’t see the original comment. Is the assembly coming from a nuget package? If the package is referenced, it will be copied to be bin directory assuming your code actually references it in code using a type from the referenced assembly. Top of head, having a post build action to copy the assembly to the bin folder?