必須創建繼承自ConfigurationSection的對象才能進行配置數據讀寫操作
class ConfigSectionData : ConfigurationSection
{
[ConfigurationProperty(
public int Id
{
get { return (int)this[
set { this[
}
[ConfigurationProperty(
public DateTime Time
{
get { return (DateTime)this[
set { this[
}
}
Configuration config = ConfigurationManager
ConfigSectionData data = new ConfigSectionData()
data
data
config
config
上面的例子是操作nfig
需要注意的 VS
如果我們需要操作非缺省配置文件
ExeConfigurationFileMap file = new ExeConfigurationFileMap()
file
Configuration config = ConfigurationManager
ConfigSectionData data = new ConfigSectionData()
data
data
config
config
如果我們不希望在根節點下寫入配置數據
ExeConfigurationFileMap file = new ExeConfigurationFileMap()
file
Configuration config = ConfigurationManager
ConfigurationUserLevel
ConfigSectionData data = new ConfigSectionData()
data
data
config
config
config
下面就是生成的配置文件
ExeConfigurationFileMap file = new ExeConfigurationFileMap()
file
Configuration config = ConfigurationManager
ConfigSectionData data = config
//ConfigSectionData data = config
if (data != null)
{
Console
Console
}
在寫入 ConfigurationSectionGroup 和 ConfigurationSection 前要判斷同名配置是否已經存在
file
Configuration config = ConfigurationManager
ConfigSectionData data = new ConfigSectionData()
data
data
ConfigurationSectionGroup group
if (group
config
ConfigurationSection data = group
if (add == null)
config
else
{
group
group
// 或者直接修改原配置對象
//ConfigSectionData configData = add as ConfigSectionData;
//configData
//configData
}
config
刪除ConfigurationSectionGroup config
//config
config
刪除ConfigurationSection config
//config
if (config
{
config
//config
}
config
可以使用 ConfigurationManager
ConfigurationManager還提供了AppSettings
比如ConfigSectionData裡面
using System
using System
using System
using System
using System
// 要寫入配置文件的自定義類
class CustomData
{
public CustomData(string s)
{
this
}
private string s;
public string S
{
get { return s; }
set { s = value; }
}
}
// 自定義的轉換器(演示代碼省略了類型判斷)
class CustomConvert : ConfigurationConverterBase
{
public override bool CanConvertFrom(ITypeDescriptorContext ctx
{
return (type == typeof(string))
}
public override object ConvertTo(ITypeDescriptorContext ctx
{
return (value as CustomData)
}
public override object ConvertFrom(ITypeDescriptorContext ctx
{
return new CustomData((string)data)
}
}
class ConfigSectionData : ConfigurationSection
{
[ConfigurationProperty(
public int Id
{
get { return (int)this[
set { this[
}
[ConfigurationProperty(
public DateTime Time
{
get { return (DateTime)this[
set { this[
}
[ConfigurationProperty(
[TypeConverter(typeof(CustomConvert))] // 指定轉換器
public CustomData Custom
{
get { return (CustomData)this[
set { this[
}
}
public class Program
{
static void Main(string[] args)
{
Configuration config = ConfigurationManager
ConfigSectionData data = new ConfigSectionData()
data
data
data
config
config
// 讀取測試
ConfigSectionData configData = (ConfigSectionData)config
Console
}
} 保存後的配置文件
From:http://tw.wingwit.com/Article/program/net/201311/13806.html