【问题标题】:Updates to custom configuration section do not write to app.config自定义配置部分的更新不会写入 app.config
【发布时间】:2011-05-09 19:43:53
【问题描述】:

经过一天的大部分研究,我仍然无法确定为什么以下代码无法按预期工作。

    bool complete = false;
    ...
    Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);                
    BatchCompiler bc = new BatchCompiler(cfg.AppSettings.Settings);

    ... do stuff with bc ...

    // Store the output of the operation.
    BatchCompilerConfiguration bcc = (BatchCompilerConfiguration)ConfigurationManager.GetSection("BatchCompiler");
    bcc.FilesCopied = complete;
    bcc.OutputPath = bc.OutputPath;
    cfg.Save(); // This does not write the modified properties to App.Config.
    //cfg.SaveAs(@"c:\temp\blah.config") // This creates a new file Blah.Config with the expected section information, as it should.

BatchCompilerConfiguration 的定义:

public sealed class BatchCompilerConfiguration : ConfigurationSection
{
    public BatchCompilerConfiguration()
    {
    }

    public override bool IsReadOnly()
    {
        return false;
    }

    [ConfigurationProperty("filesCopied", DefaultValue = "false")]
    public bool FilesCopied
    {
        get { return Convert.ToBoolean(base["filesCopied"]); }
        set { base["filesCopied"] = value; }
    }

    [ConfigurationProperty("outputPath", DefaultValue = "")]
    public string OutputPath
    {
        get { return Convert.ToString(base["outputPath"]); }
        set { base["outputPath"] = value; }
    }
}        

以下是 App.Config 中的相关部分:

<configSections>
    <section name="BatchCompiler" type="BatchCompiler.BatchCompilerConfiguration, BatchCompiler" />
</configSections>

<BatchCompiler filesCopied="false" outputPath="" />

我查看了http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx、有关 ConfigurationManager 的 MSDN 文章和参考资料,以及这里的几个现有问题,包括:

我不希望必须编写一个完整的自定义元素实现来存储我要存储的数据。但是,如果这是确保将更新信息写入 App.Config 文件的唯一方法,我会写一个。请看一下,让我知道我错过了什么。

【问题讨论】:

    标签: .net configuration c#-2.0


    【解决方案1】:

    如果 google 搜索将您带到这个问题,请注意:

    ConfigurationManager.GetSection("BatchCompiler") 提供了一个 BatchCompiler 实例,其属性设置为 BatchCompiler 类的自定义属性的 DefaultValue。

    但是,它是只读的。如果你仔细想想,这是有道理的。您还没有告诉 ConfigurationManager 使用哪个文件,那么如何持久保存更改?

    BatchCompilerConfiguration 允许读/写,因为实现中的捷径。如果继承的 IsReadOnly 方法返回 true,则原始海报不应允许设置值。

    要获得读/写部分,请使用

    BatchCompilerConfiguration sectionconfig =(BatchCompilerConfiguration)ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections["BatchCompiler"];
    

    【讨论】:

      猜你喜欢
      • 2011-01-30
      • 2011-10-02
      • 2012-04-05
      • 2015-07-05
      • 2011-05-25
      • 2012-10-04
      • 1970-01-01
      • 2011-11-04
      • 2010-10-20
      相关资源
      最近更新 更多