經過大部分時間的研究後,我仍無法確定爲什麼下面的代碼無法按預期工作。對自定義配置部分的更新不寫入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的參考資料,以及這裏包括的幾個現有問題:
- Custom Configuration in .Net
- Reload configuration settings...
- Problem implementing Custom Configuration...
- 和其他幾個人。
我不希望必須編寫完整的自定義元素實現來存儲我試圖存儲的數據。但是,如果這是確保將更新的信息寫入App.Config文件的唯一方法,那麼我會寫一個。請看一下,讓我知道我錯過了什麼。
正在編輯從upvoting答案預防嗎? – 2014-02-16 12:35:25