我需要在我的app.config中的自定义配置部分之一中更新值。是否有一个很好的例子说明如何做到这一点?
<mySection>
<level1>
<add data1="444"/>
</level1>
</mySection>
我想以编程方式将444更新为555。
最佳答案
假设您的配置存储在application.exe.config中,则应该可以进行以下操作。
void ModifyLevel1Value(int newValue)
{
Configuration exeConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
MySection section = (MySection)exeConfiguration.GetSection("mySection");
// Modify value, or whatever is sensible in your program
section.LevelsCollection["data1"] = newValue;
exeConfiguration.Save();
}
我不确定这是否适用于web.config,因为我对Web应用程序及其配置几乎没有经验。
此技术将重写配置文件,但不会刷新任何内部配置文件缓存。要强制重新加载配置文件(在您的应用程序中可能不是问题),可以调用以下静态方法。
ConfigurationManager.RefreshSection(section);
关于c# - C#-保存自定义配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11992248/