【问题标题】:Write a section in app.config file在 app.config 文件中写一段
【发布时间】:2016-08-26 23:38:13
【问题描述】:

我查看了here 关于使用 ConfigurationManager 更改 app.config 文件的信息。这似乎在文件中的<appSettings> 下写入值。

我觉得我的问题可能是一个非常相似的变化,但我不知道该怎么做。

我在我的 app.config 文件中定义了一个 configSections 元素,例如 <section name="Example".../>,并且在配置文件中它被赋予了一些值:

<Example file="C:\temp\".../>.

如果我使用命令ConfigurationManager.GetSection("Example"),我可以得到这个值。

我想知道,有没有办法在运行时更改这个值?所以我想稍后使用ConfigurationManager.GetSection("Example"),并返回新的(更改的)值 - 如果可能的话?谢谢,

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    将这些信息放在配置文件中只是实现您所寻找的目标的一步。

    您的<Example>-node 是一个自定义部分,当时还不知道。为了使 ConfigurationManager 在运行时将您的部分解析为实际对象,您必须将您的部分定义为派生自 ConfigurationSection 的类:

    public class ExampleSection : ConfigurationSection
    {
        [ConfigurationProperty("file", IsRequired = true)]
        public string File
        {
            get
            { 
                return this["file"]; 
            }
            set
            { 
                this["file"] = value; 
            }
        }
    

    完整示例请查看this comprehensive MSDN-article

    【讨论】:

    • 谢谢你!是的,我已经检查过了,我有一个 ExampleSectionset。如果我将GetSection 的结果转换为ExampleSection,进行更改并使用config.Save,我在本地所做的编辑是否会保存到配置文件中?
    • 目前无法亲自尝试,我应该可以。试试看吧☺
    【解决方案2】:

    您可以查看此链接,这是您问题的一个很好的例子:

    update appsettings and custom configuration sections in appconfig at runtime

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-09
      • 2010-12-14
      • 2012-06-23
      • 1970-01-01
      • 2013-05-10
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多