Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I embed a file in a .NET Core executable and read it at runtime?

I have some JSON files in the same folder as my project which I can read from disk with my C# (.NET Core 3.1) app, and I'd like to read them at runtime, yet compile the whole solution to one executable.

I believe something similar was possible with Embedded Resources in .NET Framework, but can I achieve this with a .NET Core app developed in VS for Mac?

like image 688
deeBo Avatar asked Sep 13 '25 09:09

deeBo


1 Answers

The solution is similar to this answer, just slightly different for VS Mac and .NET Core 3.1.

I achieved what I was looking for by adding the files to my C# project, then setting their build action to 'Embedded Resource'. It's here in VS for Mac 2019:

EmbeddedResource in VS Mac

To read them, the syntax (assuming you're in a class within the same project as the files) is:

var assembly = typeof(MyClass).Assembly;
Stream myFile = assembly.GetManifestResourceStream("MyProject.MyFolder.MyFile.json");

// To get the text as a string
var sR = new StreamReader(myFile);
var myFilesText = sR.ReadToEnd();
sR.Close();

If you're not sure what their names are, you can list the resources with:

string[] names = assembly.GetManifestResourceNames();
like image 186
deeBo Avatar answered Sep 14 '25 22:09

deeBo