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?
With newer versions of .Net Core - 2.0 or greater - there's a specialized class
EmbeddedFileProvider
that abstract the embedded file reading. To use it, addMicrosoft.Extensions.FileProviders.Embedded
package to your application:The
EmbeddedFileProvider
allows you to create a stream reader, and use according to your scenario:People have already generally answered this, so this is a rendering of the answers into something simple.
Before using the following, the file should be added as an embedded resource to the .csproj / project.json
Usage
Method
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: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"
2.- Modify "project.json" to include the related resources.
In my case:
3.- Access the embedded resource in code.
The key point is to use the right name on "GetManifestResourceStream" call. You have to use [assembly name].[directory].[file name].
Hope it helps someone out there ^_^.
Now that
project.json
is deprecated, you have to specify this in the.csproj
file.You can use a wildcard as shown, or just list out the files explicitly.
I have not confirmed this in documentation, but for me, it would appear the auto-generated Resource code that retrieves embedded files found in Resource.Designer.cs is now functioning again in .NET Core 3.1. I can now retrieve an embedded jpg simply by calling the Properties.Resources.MyImageName which returns a Bitmap object.