9、保存配置更改
到目前为止,我们已经研究了使用.NET 2.0的配置功能来定义和加载配置设置。对于许多应用程序来说,这是不够的。和使用一样,有许多时候必须保存配置。在上一节中,我们使用了Configuration对象,它提供给开发者一种将修改编程式地保存回配置节。唯一的先决条件就是配置对象允许有变更。让我们回顾一下原来的ExampleSection类,并使它可修改:
///
/// Gets the StringValue setting.
///
[ConfigurationProperty("stringValue", IsRequired=true)]
public string StringValue
{
get { return (string)base[s_propString]; }
set { base[s_propString] = value; }
// Allows setting to be changed
}
///
/// Gets the BooleanValue setting.
///
[ConfigurationProperty("boolValue")]
public bool BooleanValue
{
get { return (bool)base[s_propBool]; }
set { base[s_propBool] = value; }
// Allows setting to be changed
}
///
/// Gets the TimeSpanValue setting.
///
[ConfigurationProperty("timeSpanValue")]
public TimeSpan TimeSpanValue
{
get { return (TimeSpan)base[s_propTimeSpan]; }
set { base[s_propTimeSpan] = value; }
// Allows setting to be changed
}
///
/// Override the Properties collection and return our custom one.
///
public override ConfigurationPropertyCollection Properties
{
get { return s_properties; }
}
#endregion
正如你所看到的,更改基本的上由.NET 2.0提供的对象模型配置。简单地添加setters到配置属性上,允许他们在代码中被修改。ConfigurationElement,这是最终在每个配置类,你可以写的根源,处理所有底层复杂的东西确保修改是验证地、可转换地、有效地保存到.config文件中。要使ConfigurationElementCollection可修改,必须添加方法编辑集合。我们之前的ExampleThingElementCollection类添加一些方法使它可修改:
public void Add(ThingElement thing)
{
base.BaseAdd(thing);
}
public void Remove(string name)
{
base.BaseRemove(name);
}
public void Remove(ThingElement thing)
{
base.BaseRemove(GetElementKey(thing));
}
public void Clear()
{
base.BaseClear();
}
public void RemoveAt(int index)
{
base.BaseRemoveAt(index);
}
public string GetKey(int index)
{
return (string)base.BaseGetKey(index);
}
#endregion
一定要记住添加setters到配置元素集合包括的配置元素。添加一些公有的构造器对简化创建和填充配置元素到集合非常有用。一旦你已经做了必要的修改允许你的配置设置能在运行时修改,你可以调用Configuration类的Save()方法。Save()方法有三种不同的重载,允许你控制究竟要保存什么和强迫保存,即使没有变化。
Configuration.Save() - 仅保存修改了的值
Configuration.Save(ConfigurationSaveMode) - 保存指定类别的修改,如果存在修改
Configuration.Save(ConfigurationSaveMode, bool) - 保存指定类别的修改,迫使进行保存,如果第二个参数为true
ConfigurationSaveMode枚举具有以下值:
Full - 保存所有配置属性,不管是否有所变化
Modified - 保存已修改的属性,即使当前的值和原来是一样的
Minimal - 保存已经修改且和原来值不一样的属性
Configuration对象也有一个SaveAs()方法,他有跟Save()方法一样的基本重载。SaveAs()方法要求一个文件名作为第一个参数,表示要将配置文件保存到的路径和文件名。