2011-05-09 47 views
3

经过大部分时间的研究后,我仍无法确定为什么下面的代码无法按预期工作。对自定义配置部分的更新不写入app.config

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

如果谷歌搜索给你带来了这个问题,注意:与

ConfigurationManager.GetSection(“BatchCompiler”)提供BatchCompiler的设置为类BatchCompiler的自定义属性的默认值属性的实例。

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

BatchCompilerConfiguration允许读/写,因为执行速度很快。如果继承的IsReadOnly方法返回true,则原始海报不应允许设置值。

为了得到一个读/写部分,使用

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

正在编辑从upvoting答案预防吗? – 2014-02-16 12:35:25