如何将嵌套元素添加到 app.config?

How can I add nested elements to app.config?

任何人都可以帮助我如何使用 c# 在 app.config 文件中设置嵌套值,这可能吗? 我已经直接读到app.config了,最好不要用Properties.Settings。 但这不是必需的。

我英语不好。如果你能帮助我,请给我一些简单的英文或代码。

<?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>

您可以尝试使用以下代码将 json 数据添加到您的 app.config。

我建议您可以使用 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; }
    }

结果: