0

I have to say this is not a perfect world stackoverflow problem where I'm stuck with a code level problem But I want to know how I can full fill the following requirement. Any Suggestion/advice would be great

I have a main folder , which contains many sub-folders . Each of these subfolders are expected to have a FieServer.config file which has data in JSON format as shown in the code below.

{
  "name": "Max",
  "age": "six",
  "gender": "Male",
  "country": "india",
}

I want to know how I can Read from the file and store the 2 keys "Name" and "Country" along with its respective values as variables to be used in my C# project.

Any suggestions for the above requirement

Tim
  • 398
  • 2
  • 6
  • 13
Devin
  • 239
  • 1
  • 2
  • 9
  • You can first read the FieServer.config file as string and then use the Newtonsoft.Json library to read/deserialize the json string. https://www.newtonsoft.com/json/help/html/DeserializeWithJsonSerializerFromFile.htm https://www.newtonsoft.com/json/help/html/JObjectProperties.htm – Jaydeep Jadav Jul 25 '19 at 05:58
  • Possible duplicate of [How can I parse JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c) – Reyan Chougle Jul 25 '19 at 05:58
  • What is a your C# project type? There's a lot of helper methods to work with configuration depending on the project type. – kovac Jul 25 '19 at 06:01
  • @swdon this is actually a WPF project – Devin Jul 25 '19 at 06:04
  • Answers [here](https://stackoverflow.com/questions/53605249/json-configuration-in-full-net-framework-console-app/53609598) look feasible. – kovac Jul 25 '19 at 06:09

2 Answers2

0

you can see this web How to read and write a JSON file in C#

0

Your best option will be to first prepare an object to be used for the data. i.e.

public class FileConfigData 
{ 
  public string Name { get; set; }
  public string Country {get; set; }
}

Then just use any json serializer to transform the JSON to an object. Here's an example with json.Net lib: var configData = JsonConvert.DeserializeObject(File.ReadAllText(CONFIG_FILE_PATH)));

To get all the files into a array you can use:

string[] fileConfigs = Directory.GetFiles("path/to/dir", "FieServer.config", SearchOption.AllDirectories);

and then iterate the array like this:

List<FileConfigData> configList = new List<FileConfigData>();
foreach (var file in fileConfigs){
   var configData = JsonConvert.DeserializeObject<FileConfigData>(File.ReadAllText(CONFIG_FILE_PATH)));
configList.Add(configData);
 }

I advise you also to check the links @Willseed and @Marc posted as well as https://stackoverflow.com/a/12332495/2483016

TGN12
  • 123
  • 1
  • 8