C#中配置文件的读写

来源:互联网 发布:mac下制作win10安装u盘 编辑:程序博客网 时间:2024/05/21 00:18
 

在microsoft的dotnet环境中,首推的是xml格式的配置文件(dotnet下实际上是.config格式的),而非以前的ini或者registry.
就.config格式的配置文件dotnet1.1和dotnet2.0也有着很大的变化, 比较显著的差异有:
(1)dotnet1.1中使用的是ConfigurationSettings
而dotnet2.0中使用的是ConfigurationManager
(2)dotnet1.1中的配置文件仅支持读操作,而不支持写操作,如果要完成写操作,则需要用户自己写一个xml文件的写函数来完成(本文也将给出一个例子)
而dotnet2.0中的ConfigurationManager已经可以实现配置文件节点的读写操作,并可以创建自己的group,secton和element,相对来说功能更强大.

本文只是起到一个抛砖引玉的作用,只展现了dotnet2.0的一部分特性,如果要做一些其他的操作,或者想把异常情况考虑的更全面一些,读者可以参考MSDN或者其他资料来做进一步的完善.要使用dotnet2.0中的配置文件功能,需要引用一下类:
using System.Configuration; // configuration setting
using System.Xml;

一、配置文件的读
/*string dbPath = ConfigurationSettings.AppSettings[textBoxkey.Text];

MessageBox.Show(String.Format("DatabasePath = {0}", dbPath));

string data = ConfigurationSettings.AppSettings["Data"];
int iData = int.Parse(data);

MessageBox.Show(String.Format("Data = {0}", iData));*/
// Get the application configuration file.
try
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");

try
{
textBoxPrompt.Text = appSection.Settings[textBoxkey.Text].Value;
}
catch (NullReferenceException)
{
textBoxPrompt.Text = "no such element";
}

}
catch (Exception ex)
{
textBoxPrompt.Text = String.Format("Exception catch: {0}", ex.Message);
string s = ex.ToString();
}
上面注释部分使用的是dotnet1.1中的功能

二、配置文件的写
try
{
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");
appSection.Settings[textBoxkey.Text].Value = textBoxvalue.Text;
config.Save();
}
catch (Exception ex)
{
textBoxPrompt.Text = String.Format("Exception catch: {0}", ex.Message);
}

在dotnet1.1中要想实现写操作则需要用户自己来实现,以下代码仅仅是一个例子
private void SaveConfig(string Key, string Value)
{
XmlDocument doc = new XmlDocument();
//获得配置文件的路径
string strFileName = Application.StartupPath + ".ConfigurationSettingTest.vshost.exe.config";
doc.Load(strFileName);
//找出名称为add的所有元素
XmlNodeList nodes = doc.GetElementsByTagName("add");
for (int i = 0; i < nodes.Count; i++)
{
//获得当前元素的key属性
XmlAttribute att = nodes[i].Attributes["key"];
//根据元素的第一个属性来判断当前的元素是不是目标元素
if (att.Value == Key)
{
//对目标元素中的第二个属性赋值
att = nodes[i].Attributes["value"];
att.Value = Value;
break;
}
}
//保存上面的修改
doc.Save(strFileName);
}

三、实现自定义sector
(1)先定义一些element和elementcollections
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;

namespace ConfigurationSettingTest
{
// element defination
public class ListItemsElement : ConfigurationElement
{
[ConfigurationProperty("name", DefaultValue = "",
IsKey = true, IsRequired = true)]
public string Name
{
get { return ((string)(base["name"])); }
set { base["name"] = value; }
}
[ConfigurationProperty("value", DefaultValue = "",
IsKey = false, IsRequired = false)]
public string Value
{
get
{
return ((string)(base["value"]));
}
set
{
base["value"] = value;
}
}

[ConfigurationProperty("secquence", DefaultValue = "",
IsKey = false, IsRequired = false)]
public string Secquence
{
get
{
return ((string)(base["secquence"]));
}
set
{
base["secquence"] = value;
}
}

[ConfigurationProperty("action", DefaultValue = "",
IsKey = false, IsRequired = false)]
public string Action
{
get
{
return ((string)(base["action"]));
}
set
{
base["action"] = value;
}
}
}

[ConfigurationCollectionAttribute(typeof(ListItemsElement))]
public class ListItemsCollection : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new ListItemsElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ListItemsElement)(element)).Name;
}
public void Add(ListItemsElement element)
{
this.BaseAdd(element);
}
public void Remove(string key)
{
this.BaseRemove(key);
}
public void Clear()
{
this.BaseClear();
}
public ListItemsElement this[int idx]
{
get { return (ListItemsElement)this[idx]; }
}
}

public class ListElementsSection : ConfigurationSection
{
[ConfigurationProperty("listItems")]
public ListItemsCollection ListItems
{
get
{
return ((ListItemsCollection)(base["listItems"]));
}
}
}

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)再添加相应的element或者sector,具体方法参见MSDN
/*System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
ConfigSectionData data = new ConfigSectionData();
data.ID = 1000;
data.Time = DateTime.Now;

//在加入之前应该先测试是否是存在同样的section,如果有的话先删除,否则会报异常

ConfigSectionData test = config.Sections["TestSection"] as ConfigSectionData;
if (test == null) // not already exist
{
config.Sections.Add("TestSection", data);
}
else // exist
{
config.Sections.Remove("TestSection");
config.Sections.Add("TestSection", data);
}

//ConfigSectionData section = (ConfigSectionData)config.GetSection("TestSection");
config.Save();*/

System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);

// ListItemsCollection listcollection;

//在加入之前应该先测试是否是存在同样的section,如果有的话先删除,否则会报异常


ListElementsSection test = config.Sections["TestSection"] as ListElementsSection;
if (test == null) // not already exist
{
config.Sections.Add("TestSection", new ListElementsSection());
}
else // exist
{
config.Sections.Remove("TestSection");
config.Sections.Add("TestSection", new ListElementsSection());
}

ListElementsSection appSection = (ListElementsSection)config.GetSection("TestSection");
ListItemsElement listElement = new ListItemsElement();
listElement.Name = "Guanjinzhong";

appSection.ListItems.Add(listElement);

config.Save();

}
注释部分是添加系统默认sector中的element的方法

注意:以上代码都是直接从项目代码中抽取出来的,没有做什么更改,所以不能直接编译运行,在这里贴出来仅作为一个参考