2011-05-09 46 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