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

5
  • You can first read the FieServer.config file as string and then use the Newtonsoft.Json library to read/deserialize the json string. newtonsoft.com/json/help/html/… newtonsoft.com/json/help/html/JObjectProperties.htm Commented Jul 25, 2019 at 5:58
  • Possible duplicate of How can I parse JSON with C#? Commented Jul 25, 2019 at 5:58
  • What is a your C# project type? There's a lot of helper methods to work with configuration depending on the project type. Commented Jul 25, 2019 at 6:01
  • @swdon this is actually a WPF project Commented Jul 25, 2019 at 6:04
  • Answers here look feasible. Commented Jul 25, 2019 at 6:09

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.