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?
Embedded resource has no predefined structure: it is just a named blob of bytes. So called “. resx” file is a special kind of embedded resource. It is a string -to-object dictionary that maps a name to an object. The object may be a string , an image, an icon, or a blob of bytes.
Open Solution Explorer add files you want to embed. Right click on the files then click on Properties. In Properties window and change Build Action to Embedded Resource.
Embedded files and their Advantages Embedded files are called as Embedded Resources and these files can be accessed at runtime using the Assembly class of the System. Reflection namespace. Any file within the project can be made into an embedded file.
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:
Add your embedded file(s) as usual.
Example: some FONT files on a directory named "_fonts"
Modify "project.json" to include the related resources.
In my case:
"buildOptions": { "embed": { "include": [ "_fonts/*.ttf" ] } },
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With