必須創建繼承自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
ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file
Configuration config = ConfigurationManager
ConfigSectionData data = config
//ConfigSectionData data = config
if (data != null)
{
Console
Console
}
在寫入 ConfigurationSectionGroup 和 ConfigurationSection 前要判斷同名配置是否已經存在
另外如果配置文件被其他Configuration對象修改
ExeConfigurationFileMap file = new ExeConfigurationFileMap();
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
或者使用 System
ConfigurationManager還提供了AppSettings
引用至 ggy
比如ConfigSectionData裡面
除了簡單類型之外
using System;
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
}
}
保存後的配置文件
更詳細的信息可以看 MSDN 中關於 System
From:http://tw.wingwit.com/Article/program/net/201311/12863.html