Embedded resource in .Net Core libraries

Don Tomato picture Don Tomato · Aug 4, 2016 · Viewed 65.5k times · Source

I just have started looking into .Net Core, and I don't see classical resources and anything what looks like resources. In classical .Net class libraries I was able to add, for example, text filtes with some script to my project, than I can add these files to project's resources. After that I could easily use that by the following way:

Connection.Execure(Properties.Resources.MySuperScript);

I see that there isn't such feature in .Net Core libraries, at least I don't see. Is there an alternative in .Net Core to store some statical data as an embedded resource in libraries? And how to use that if it exists?

Answer

Nacho Coll picture Nacho Coll · Dec 12, 2016

UPDATE:

.NET Core 1.1 and later have dropped project.json and returned to .csproj files. This changes Step 2, but not all that much. The necessary lines are very similar:

<ItemGroup>
  <Content Remove="_fonts/OpenSans.ttf" />
  <Content Remove="_fonts/OpenSans-Bold.ttf" />
  <Content Remove="_fonts/OpenSans-Italic.ttf" />
</ItemGroup>
<ItemGroup>
  <EmbeddedResource Include="_fonts/OpenSans.ttf" />
  <EmbeddedResource Include="_fonts/OpenSans-Bold.ttf" />
  <EmbeddedResource Include="_fonts/OpenSans-Italic.ttf" />
</ItemGroup>

There may be a similar *.tff form; unconfirmed.

Steps 1 and 3 are unchanged.


To use embedded resources in .NET Core 1.0 project do the following:

  1. Add your embedded file(s) as usual.

    Example: some FONT files on a directory named "_fonts"

    enter image description here

  2. Modify "project.json" to include the related resources.

    In my case:

     "buildOptions": {
        "embed": {
          "include": [
            "_fonts/*.ttf"    
          ]
        } 
      },
    
  3. Access the embedded resource in code.

    var assembly = typeof(MyLibrary.MyClass).GetTypeInfo().Assembly;
    Stream resource = assembly.GetManifestResourceStream("MyLibrary._fonts.OpenSans.ttf");
    

    The key point is to use the right name on GetManifestResourceStream call. You have to use [assembly name].[directory].[file name].