2

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?

deeBo
  • 836
  • 11
  • 24
  • 1
    Does this answer your question? [Embedded resource in .Net Core libraries](https://stackoverflow.com/questions/38762368/embedded-resource-in-net-core-libraries) – David Browne - Microsoft Jan 26 '20 at 00:15
  • That answer seems like it might work, thank you. I will try it tomorrow and close my question as duplicate if it solves the issue. – deeBo Jan 26 '20 at 01:16
  • 1
    The answer you linked was almost correct, although it's slightly different for .NET Core 3.1, the property name etc isn't *quite* the same. – deeBo Jan 26 '20 at 15:42

1 Answers1

3

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();
deeBo
  • 836
  • 11
  • 24