0

Can anyone please help me how can I set nested values in the app.config file using c#, is it possible at all? I already read directly to app.config and it's better not to use Properties.Settings. But this is not a requirement.

I'm not good at English. If you can help me, please show me some simple English or code.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="class" value='[
      {"Name":"John","Value":"82"},
      {"Name":"Peter","Value":"92"},
      {"Name":"Sam","Value":"64"},
    ]'/>
  </appSettings>
</configuration>
Russ Cam
  • 124,184
  • 33
  • 204
  • 266
okaken
  • 13
  • 4
  • You could define a custom configuration like here https://stackoverflow.com/q/3935331/2030565. But it's probably easier to define a pointer to a file name in your _app.config_ `` that points to a formatted _settings.json_ file and deserialize that into a POCO. – Jasen Apr 28 '21 at 00:59

1 Answers1

0

You can try the following code to add json data to your app.config.

I suggest that you can read the file by using linq to xml.

static void Main(string[] args)
        {
            List<Student> list = new List<Student>();
            list.Add(new Student { Name = "John", Value = 82 });
            list.Add(new Student { Name = "John", Value = 82 });
            list.Add(new Student { Name = "John", Value = 82 });
            var json = JsonConvert.SerializeObject(list, Formatting.None);
            string path = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..")) + "\\App.config";
            XDocument doc = XDocument.Load(path);

            doc.Element("configuration").Add(new XElement("appSettings", ""));
            doc.Descendants("appSettings").First().Add(new XElement("add", ""));
            doc.Descendants("add").First().Add(new XAttribute("key", "class"));
            doc.Descendants("add").First().Add(new XAttribute("value", json));

            doc.Save(path);
            string txt = File.ReadAllText(path);
            txt=txt.Replace("&quot;", "\"");
            File.WriteAllText(path,txt);

        }

 public class Student
    {
        public string Name { get; set; }

        public int Value { get; set; }
    }

Result:

enter image description here

Jack J Jun
  • 5,633
  • 1
  • 9
  • 27
  • Thank you for great answer! Your answer is concise and meets all requirements. – okaken Apr 29 '21 at 02:54
  • @okaken, I am glad to hear that your problem has been solved, you can click '✔' to mark the reply as an answer. It will also help others to solve the similar issue. – Jack J Jun Apr 29 '21 at 03:00
  • sorry. I use this site for the first time. I didn't know how to use it. great thanks agein. – okaken Apr 30 '21 at 02:16