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.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.
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.json file 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
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
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.