1 Configuration结构
配置文件是我们经常使用的,和ini文件相比,它的可读性好,扩展性强,能比较容易的保存复杂的配置。我们常用的节点如下:
appsetting节点,包含客户端应用程序配置,以键值对的方式保存诸如数据库连接字符串、文件路径等信息。
connectionStrings节点,以名值对的方式提供数据库连接字符串的集合。
configSections节点,包含指定的配置节和名字空间定义,包含子元素section
,sectionGroup。
大致的配置文件结构如下:
<configuration>
<connectionStrings>
<clear/>
<addname="LocalSqlServer"connectionString="sqlserver数据库连接"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<appSettingsfile="">
<clear/>
<addkey="appSet"value="应用程序配置"/>
<addkey="appSet2"value="应用程序配置2"/>
</appSettings>
<configSections>
<sectionGroupname="jecjk">
<sectionname="TheLoverCompany"type="System.Configuration.NameValueSectionHandler, System,Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</sectionGroup>
<MyNameValue>
<addkey="key1"value="join" />
<addkey="key1"value="jeffery" />
</MyNameValue>
<MyDictionary>
<addkey="d1"value="1234" />
<addkey="d2"value="1235" />
</MyDictionary>
<MySingleTagprop1 ="loacal"prop2="*****" />
<CustomSection>
<addkey ="myself"value="china god" />
<addkey ="myself"value="american god" />
</CustomSection>
< jecjk >
<TheLoverCompanyName="1号店"Address="城南路1000号"Legal="Mr wu" />
</ jecjk >
</configSections>
2 appsetting 节点
读取appsetting节点:
public static void ReadAppSetting()
{
NameValueCollection nv =ConfigurationManager.AppSettings;
foreach (var itemin nv.AllKeys)
{
Console.WriteLine("appsetting key: {0} ---- value: {1}",item,nv[item]);
}
Console.WriteLine();
}
3 connectStrings 节点
读取connectionStrings节点:
public static void ReadConnectionStrings()
{
ConnectionStringSettingsCollection coll =ConfigurationManager.ConnectionStrings;
Console.WriteLine("ConnectStrings节点是否只读:{0}",ConfigurationManager.ConnectionStrings["LocalSqlServer"].IsReadOnly());
foreach (ConnectionStringSettings itemin coll)
{
Console.WriteLine("{0}--{1}--{2}",item.Name,item.ProviderName,item.ConnectionString);
}
}
4 configSections节
public staticvoid ShowConfigSection()
{
JecConfigSection jec =ConfigurationManager.GetSection("TheJecjk")asJecConfigSection;
if (null == jec)
{
Console.WriteLine("jecConfigSection is null");
return;
}
Console.WriteLine("公司名称:{0}", jec.CompanyName);
Console.WriteLine("公司地址:{0}{1}", jec.Address.Province,jec.Address.City);
}
class JecConfigSection : ConfigurationSection
{
//定义一个attribute
[ConfigurationProperty("companyName", DefaultValue ="跨国贸易", IsRequired =true)]
public string CompanyName
{
get { return (string)this["companyName"]; }
set { this["companyName"] = value; }
}
//定义一个element
[ConfigurationProperty("address")]
public AddressElement Address
{
get {
return (AddressElement)this["address"];
}
set {
this["address"] =value;
}
}
public static void SaveConfig(JecConfigSection jec)
{
Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
JecConfigSection jecSection = config.GetSection("TheJecjk")asJecConfigSection;
if (jecSection == null)
{
jecSection = new JecConfigSection();
jecSection.CompanyName = jec.CompanyName;
jecSection.Address.Province = jec.Address.Province;
jecSection.Address.City = jec.Address.City;
config.Sections.Add("TheJecjk", jecSection);
}
else
{
config.Sections.Remove("TheJecjk");
jecSection.CompanyName = jec.CompanyName;
jecSection.Address.Province = jec.Address.Province;
jecSection.Address.City = jec.Address.City;
config.Sections.Add("TheJecjk", jecSection);
}
config.Save(ConfigurationSaveMode.Modified);
}
}
class AddressElement : ConfigurationElement
{
[ConfigurationProperty("province",DefaultValue="浙江",IsRequired=true)]
[StringValidator(InvalidCharacters="~!@#$%^&*()[]{}/;'\"|\\",MinLength = 1,MaxLength=10)]
public string Province
{
get { return (string)this["province"]; }
set { this["province"] = value; }
}
[ConfigurationProperty("city",DefaultValue="嘉兴")]
public string City
{
get { return (string)this["city"]; }
set { this["city"] = value; }
}
}
5 加密节点
使用DataProtectionConfigurationProvider提供程序对connectionString节点进行加密/解密。
public staticvoid ToggleConfigEncryption()
{
// Takes the executable file name without the
// .config extension.
try
{
// Open the configuration file and retrieve
// the connectionStrings section.
Configuration config =ConfigurationManager.
OpenExeConfiguration("ConsoleApplication1.exe");
ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
Console.WriteLine("Protected={0}",
section.SectionInformation.IsProtected);
if (section.SectionInformation.IsProtected)
{
// Remove encryption.
section.SectionInformation.UnprotectSection();
}
else
{
// Encrypt the section.
section.SectionInformation.ProtectSection(
"DataProtectionConfigurationProvider");
}
// Save the current configuration.
config.Save();
Console.WriteLine("Protected={0}",
section.SectionInformation.IsProtected);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}