namespace System.Configuration;
1. 建立配置節類
必須建立繼承自ConfigurationSection的對象才能進行配置資料讀寫操作,ConfigurationSection提供了索引器用來擷取和設定配置資料,需要注意的是擁有ConfigurationProperty特性的屬性才會被儲存,並且名稱要保持大小寫完全一致,如下面的代碼中,所有的"id"必須保持一樣。class ConfigSectionData : ConfigurationSection
{
[ConfigurationProperty("id")]
public int Id
{
get { return (int)this["id"]; }
set { this["id"] = value; }
}
[ConfigurationProperty("time")]
public DateTime Time
{
get { return (DateTime)this["time"]; }
set { this["time"] = value; }
}
}
2. 建立設定檔操作對象Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;
config.Sections.Add("add", data);
config.Save(ConfigurationSaveMode.Minimal);
上面的例子是操作 app.config,在根節點(configuration)下寫入名稱為"add"的配置資料。<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="add" type="ConsoleApplication1.ConfigSectionData, ... />
</configSections>
<add id="1000" time="02/18/2006 21:51:06" />
</configuration>
需要注意的 VS2005 在IDE模式下會將資訊寫入 *.vshost.exe.config,並且在程式關閉時覆寫該檔案,因此您可能看不到您寫入的配置資料,只要在資源管理其中執行 *.exe 檔,您就可以在 *.exe.config 檔案中看到結果了。
如果我們需要操作非預設設定檔,可以使用ExeConfigurationFileMap對象。ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;
config.Sections.Add("add", data);
config.Save(ConfigurationSaveMode.Minimal);
如果我們不希望在根節點下寫入配置資料,可以使用ConfigurationSectionGroup對象。ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;
config.SectionGroups.Add("group1", new ConfigurationSectionGroup());
config.SectionGroups["group1"].Sections.Add("add", data);
config.Save(ConfigurationSaveMode.Minimal);
下面就是產生的設定檔。<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="group1" type="System.Configuration.ConfigurationSectionGroup, ... >
<section name="add" type="ConsoleApplication1.ConfigSectionData, ... />
</sectionGroup>
</configSections>
<group1>
<add id="1000" time="02/18/2006 22:01:02" />
</group1>
</configuration>
3. 讀取設定檔ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
ConfigSectionData data = config.SectionGroups["group1"].Sections["add"] as ConfigSectionData;
//ConfigSectionData data = config.Sections["add"] as ConfigSectionData; // 從根節讀取
if (data != null)
{
Console.WriteLine(data.Id);
Console.WriteLine(data.Time);
}
4. 寫設定檔
在寫入 ConfigurationSectionGroup 和 ConfigurationSection 前要判斷同名配置是否已經存在,否則會寫入失敗。
另外如果設定檔被其他Configuration對象修改,則儲存會失敗,並拋出異常。建議採用Singleton模式。ExeConfigurationFileMap file = new ExeConfigurationFileMap();
file.ExeConfigFilename = "test.config";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.Id = 2000;
data.Time = DateTime.Now;
ConfigurationSectionGroup group1 = config.SectionGroups["group1"];
if (group1 == null)
config.SectionGroups.Add("group1", new ConfigurationSectionGroup());
ConfigurationSection data = group1.Sections["add"] as config;
if (add == null)
config.SectionGroups["group1"].Sections.Add("add", data);
else
{
group1.Sections.Remove("add");
group1.Sections.Add("add", data);
// 或者直接修改原設定物件,前提是類型轉換要成功。
//ConfigSectionData configData = add as ConfigSectionData;
//configData.Id = data.Id;
//configData.Time = data.Time;
}
config.Save(ConfigurationSaveMode.Minimal);
5. 刪除配置節
刪除ConfigurationSectionGroup
config.SectionGroups.Remove("group1");
//config.SectionGroups.Clear();
config.Save(ConfigurationSaveMode.Minimal);
刪除ConfigurationSection
config.Sections.Remove("add1");
//config.Sections.Clear();
if (config.SectionGroups["group1"] != null)
{
config.SectionGroups["group1"].Sections.Remove("add2");
//config.SectionGroups["group1"].Sections.Clear();
}
config.Save(ConfigurationSaveMode.Minimal);
6. 其他
可以使用 ConfigurationManager.OpenMachineConfiguration() 來操作 Machine.config 檔案。
或者使用 System.Web.Configuration 名字空間中的 WebConfigurationManager 類來操作 ASP.net 設定檔。
ConfigurationManager還提供了AppSettings、ConnectionStrings、GetSection()等便捷操作。
7. 使用自訂類
2006-4-17 補充,回複 ggy 網友的疑問。
引用至
ggy比如ConfigSectionData裡面
除了簡單類型之外,可不可以有自訂的類
可以使用自訂類,不過需要定義一個轉換器。using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.ComponentModel;
// 要寫入設定檔的自訂類
class CustomData
{
public CustomData(string s)
{
this.s = s;
}
private string s;
public string S
{
get { return s; }
set { s = value; }
}
}
// 自訂的轉換器(示範代碼省略了類型判斷)
class CustomConvert : ConfigurationConverterBase
{
public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type)
{
return (type == typeof(string));
}
public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
{
return (value as CustomData).S;
}
public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data)
{
return new CustomData((string)data);;
}
}
class ConfigSectionData : ConfigurationSection
{
[ConfigurationProperty("id")]
public int Id
{
get { return (int)this["id"]; }
set { this["id"] = value; }
}
[ConfigurationProperty("time")]
public DateTime Time
{
get { return (DateTime)this["time"]; }
set { this["time"] = value; }
}
[ConfigurationProperty("custom")]
[TypeConverter(typeof(CustomConvert))] // 指定轉換器
public CustomData Custom
{
get { return (CustomData)this["custom"]; }
set { this["custom"] = value; }
}
}
public class Program
{
static void Main(string[] args)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.Id = 1000;
data.Time = DateTime.Now;
data.Custom = new CustomData("abcdefg...");
config.Sections.Add("add", data);
config.Save(ConfigurationSaveMode.Minimal);
// 讀取測試
ConfigSectionData configData = (ConfigSectionData)config.Sections["add"];
Console.WriteLine(configData.Custom.S);
}
}
儲存後的設定檔
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="add" type="..." />
</configSections>
<add id="1000" time="04/17/2006 22:06:58" custom="abcdefg..." />
</configuration>