Get a Json file from a specific folder and serialize it - c#

I need to get json file from a specific folder in my solution. the name of the json file is "plaza.json" and the folder it is in is Data. Please see image below.
How do I get this file and serialize it? I have searched for some answers but the closest is this:
using (var streamReader = new StreamReader("plaza.json"))
{
string json = streamReader.ReadToEnd();
var deserializedObject = JsonConvert.DeserializeObject<SomeClass>(json);
}
if I use that, it doesn't see my json file

using (var streamReader = new StreamReader(Server.MapPath("~/Data/plaza.json"))
{
string json = streamReader.ReadToEnd();
var deserializedObject = JsonConvert.DeserializeObject<SomeClass>(json);
}
This should work, haven’t test but check this how file will be accessed
Depending on you project type it can be server.mappath or hostingenvironment.mappath
If desktop app like win forms or wpf use this
Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Data/plaza.json");
Make sure to put copy file if modified property in build property

Related

How to save a variable's data in C# Unity? [duplicate]

This question already has an answer here:
Saving/loading data in Unity
(1 answer)
Closed last year.
I have a variable which I want to save the data to the user's device.
Ex: float score = 100;
I want to save this variable as data and load it on game run.
You can store your data in a external file like a json.
When you want to access your data to edit or just get the value, you can simply read/write it from the file
I advise you to use the library Newtonsoft.
Once you have downloaded the packages, add the following usings :
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
You can use this code to write in the file
/////Write in the file/////
//Create a dynamic object to store data
dynamic obj = new JObject();
//Set the values
obj.WorkDuration = workDuration;
obj.PauseDuration = pauseDuration;
obj.NbSessions = nbSessions;
//Write the values in the json file
File.WriteAllText(JsonFileFullname, JsonConvert.SerializeObject(obj));
And this code to get the data in the file
/////Get values from the file/////
//Create a reader object for get the content of the json file
StreamReader reader = new StreamReader(JsonFileFullname);
//Read the content of the json file
string json = reader.ReadToEnd();
//Create a dynamic object with stored data
dynamic data = JObject.Parse(json);
//Get the values
int workDuration = data.WorkDuration;
int pauseDuration = data.PauseDuration;
int nbSessions= data.NbSessions;
Your JSON file should look something like this
{"WorkDuration":300,"PauseDuration":5,"NbSessions":8}
I hope my answer will be of use to you. If you have any questions, don't hesitate to ask them

Convert an IFile (JSON File) to MyObject

I upload a JSON file with a HTML form as explained here in the first paragraph. I accept only 1 file at a time so this is my controller:
public IActionResult Upload(IFormFile file)
{
}
Now I want to convert the file containing JSON to an object. Just like this accepted answer of Cuong Le. How do I convert the file to lets say MyObject? How do i deserialize the file?
(Newtonsoft is the lib to import right?)
You can read the text from the file and then convert to JSON. You can try something like,
string fileContent = null;
using (var reader = new StreamReader(file.OpenReadStream()))
{
fileContent = reader.ReadToEnd();
}
var result = JsonConvert.DeserializeObject<MyObject>(fileContent );
Yes, you can use Newtonsoft NuGet package for deserializing.

Xamarin Android System.IO.FileNotFoundException: Could not find file Exception

I use Visual Studio 2015 with Xamarin Android.
I want to read some JSON data from file, but I keep getting this System.IO.FileNotFoundException, even though I have set my files properties "Build: Content, Copy to Output Directory: Copy if newer" and I can see the file physically in my build folder.
I use this code:
var path = #"AedJson.json";
using (var streamReader = new StreamReader(path))
{
string json = streamReader.ReadToEnd();
//JObject o1 = JObject.Parse(json);
}
The exact exception is:
System.IO.FileNotFoundException: Could not find file "/AedJson.json".
Error Picture
You need to add your json file to your Xamarin.Android project as an Asset (within the Assets folder) and flag it as an AndroidAsset build type, then you can use the AssetManager to read it.
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader (assets.Open ("AedJson.json")))
{
string json = sr.ReadToEnd ();
}
Ref: Using Android Assets
I'm not sure it really is an error, but looking at the error, it seems like the path is incorrect. Do you really need to save your file precisely where you're actually saving it ? If not, try this :
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile.txt");
using (var streamReader = new StreamReader(filename))
{
string json = streamReader.ReadToEnd();
//JObject o1 = JObject.Parse(json);
}
Use this path to save and to load. I'm proceeding like this for all my files and it seems to work well.
This works using Microsoft.Extensions.Configuration.Json
Set json file build action in properties as embedded resource
Project : Client
FileFolder : Configuration
FileName : appsettings.json
JSON :
{
"Rest": {
"Server": "192.168.0.199",
"Port": "5003"
}
}
CODE:
string Namespace = "Client.Configuration";
string FileName = "appsettings.json";
Assembly assembly = GetType().Assembly;
Stream stream = assembly.GetManifestResourceStream($"{Namespace}.{FileName}");
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonStream(stream);
var root = configurationBuilder.Build();
IConfigurationSection restClientConfigration = root.GetSection("Rest");
string server = restClientConfigration.GetSection("Server").Value;
string port = restClientConfigration.GetSection("Port").Value;

Load in an unknown number of files in a specific directory

I'm trying to load an unknown number of json files in a directory using json.net (C:/users/Nathan/Documents/test)
I want to be able to add json files to this directory and no matter how many there are my program should be able to access all of them and load them as separate a jObject with unique names.
Is this even possible?
Edit I don't have code yet, I have to get ideas what direction to take for this.
Code would be something like below:
var fileNames = Directory.GetFiles(#"C:\user\Nathan\Documents\test");
foreach(var file in fileNames)
{
using (var sr = File.OpenText(file))
using (var reader = new JsonTextReader(sr))
{
var json = (JObject) JToken.ReadFrom(reader);
}
}
Use string[] fileNames = Directory.GetFiles("C:/users/Nathan/Documents/test") to get all the file names in a specific directory. Also, this can throw an exception if the directory does not exist.

Reading embedded XML file c#

How can I read from an embedded XML file - an XML file that is part of a c# project?
I've added a XML file to my project and I want to read from it. I want the XML file to compile with the project because I don't want that it will be a resource which the user can see.
Any idea?
Make sure the XML file is part of your .csproj project. (If you can see it in the solution explorer, you're good.)
Set the "Build Action" property for the XML file to "Embedded Resource".
Use the following code to retrieve the file contents at runtime:
public string GetResourceTextFile(string filename)
{
string result = string.Empty;
using (Stream stream = this.GetType().Assembly.
GetManifestResourceStream("assembly.folder."+filename))
{
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
}
return result;
}
Whenever you want to read the file contents, just use
string fileContents = GetResourceTextFile("myXmlDoc.xml");
Note that "assembly.folder" should be replaced with the project name and folder containing the resource file.
Update
Actually, assembly.folder should be replaced by the namespace in which a class created in the same folder as the XML file would have by default. This is typically defaultNamespace.folder0.folder1.folder2......
You can also add the XML file as a Resource and then address its contents with Resources.YourXMLFilesResourceName (as a string, i.e. using a StringReader).
Set the Build Action to Embedded Resource, then write the following:
using (Stream stream = typeof(MyClass).Assembly.GetManifestResourceStream("MyNameSpace.Something.xml")) {
//Read the stream
}
You can use Reflector (free from http://www.red-gate.com/products/reflector/) to find the path to the embedded XML file.
Then, it's just a matter of
Assembly a = typeof(Assembly.Namespace.Class).Assembly;
Stream s = a.GetManifestResourceStream("Assembly.Namespace.Path.To.File.xml");
XmlDocument mappingFile = new XmlDocument();
mappingFile.Load(s);
s.Close();
Add the file to the project.
Set the "Build Action" property to "Embedded Resource".
Access it this way:
GetType().Module.Assembly.GetManifestResourceStream("namespace.folder.file.ext")
Notice that the resource name string is the name of the file,
including extension, preceded by the default namespace of the project.
If the resource is inside a folder, you also have to include it in the
string.
(from http://www.dotnet247.com/247reference/msgs/1/5704.aspx, but I used it pesonally)
#3Dave really helped (up vote given), however my resource helper was in a different assembly so I did the below
public string GetResourceFileText(string filename, string assemblyName)
{
string result = string.Empty;
using (Stream stream =
System.Reflection.Assembly.Load(assemblyName).GetManifestResourceStream($"{assemblyName}.{filename}"))
{
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
}
}
return result;
}
Called by
GetResourceFileText("YourFileNameHere.ext", Assembly.GetExecutingAssembly().GetName().Name);

Categories