【问题标题】:How can I add nested elements to app.config?如何将嵌套元素添加到 app.config?
【发布时间】:2021-07-21 08:05:20
【问题描述】:

谁能帮助我如何使用 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>

【问题讨论】:

  • 您可以像这里stackoverflow.com/q/3935331/2030565 一样定义自定义配置。但是在 app.config &lt;add key="settingsJSON" value="settings.json" /&gt; 中定义一个指向格式化的 settings.json 文件并将其反序列化为 POCO 的文件名的指针可能更容易。

标签: c# .net visual-studio app-config


【解决方案1】:

您可以尝试以下代码将 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; }
    }

结果:

【讨论】:

  • 感谢您的出色回答!您的回答简洁明了,符合所有要求。
  • @okaken,很高兴听到您的问题已经解决,您可以点击“✔”将回复标记为答案。它还将帮助其他人解决类似的问题。
  • 对不起。我第一次使用这个网站。我不知道如何使用它。非常感谢agein。
猜你喜欢
  • 2023-01-22
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
相关资源
最近更新 更多