自定义配置部分的更新不会写入app.config

时间:2011-05-09 19:43:53

标签: .net configuration c#-2.0

在大部分时间研究之后,我仍然无法确定以下代码无法按预期工作的原因。

    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,相关的MSDN文章和ConfigurationManager的参考资料,以及此处的一些现有问题,包括:

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

1 个答案:

答案 0 :(得分:1)

如果谷歌搜索引导您解决此问题,请注意:

ConfigurationManager.GetSection(&#34; BatchCompiler&#34;)提供BatchCompiler的实例,其属性设置为BatchCompiler类的自定义属性的DefaultValue。

但是,只读。如果你考虑一下,这是有道理的。您还没有告诉ConfigurationManager使用哪个文件,那么如何才能保留更改?

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

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

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