Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read .JSON from embedded resource C#

I'm trying to read in a JSON file from an embedded resource. I've tried looking online but most questions are about .txt files that aren't helping.

I've already tried making the json file an embedded resource but that hasn't helped either.

var assembly = Assembly.GetExecutingAssembly();
var resourceName = "MyLibrary.Properties.Resources.MyJson.json";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))
using (StreamReader reader = new StreamReader(stream))
{
    string jsonFile = reader.ReadToEnd(); //Make string equal to full file
}

When this code is run, I get the following error: System.ArgumentNullException: 'Value cannot be null. Parameter name: stream'

like image 817
Daniel Lawton Avatar asked Jan 12 '19 14:01

Daniel Lawton


People also ask

How do you read embedded files?

Method 1: Add existing file, set property to Embedded Resource. Add the file to your project, then set the type to Embedded Resource . NOTE: If you add the file using this method, you can use GetManifestResourceStream to access it (see answer from @dtb).

What is embedded resource C#?

Embedded files are called as Embedded Resources and these files can be accessed at runtime using the Assembly class of the System.Reflection namespace. This article will illustrate, how to read and display an embedded Text file and Image file in Windows Application (Windows Forms) in C# and VB.Net.

How do I add embedded resources to Visual Studio?

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 . After that you should write the embedded resources to file in order to be able to run it.


1 Answers

This was fixed by changing

var resourceName = "MyLibrary.Properties.Resources.MyJson.json";

to this:

var resourceName = "MyLibrary.Resources.MyJson.json";

Having "Properties" in the resourceName is incorrect it seems.

like image 165
Daniel Lawton Avatar answered Oct 17 '22 21:10

Daniel Lawton