貌似没有找到直接支持读写INI文件的类, 虽然网上也有不少草根版的类可用, 很多人还是建议使用XML来做。
XML一套的东西实在是太多, 各种名字搞得眼花缭乱, 只选了两个常用方法, 封装一个类,对程序配置信息进行Get和Set即可。
SelectSingleNode返回的是XmlNode的对象, 该对象还可以继续SelectSingleNode,用于索引其下的子对象。 它的InnerText即代表的里面的文本内容, 是个string型的,直接进行读写即可。
另外考虑到客户(程序员)可能直接Set一个不存在的节点, 于是当SelectSingleNode返回null的时候, 使用CreateElement创建一个该名字的节点即可。
最后,第一次使用程序的时候, 可能该配置文件都不存在。 于是先尝试打开文件, 发生IO错误的时候新建一个, 填上基本的XML信息,添加一个Root节点。 (这节代码copy的网上某处,搞忘地方了)
一。CConfig类的代码:
class CConfig { private string _FileName; private XmlDocument _xmlDocument;
public string FileName { get { return _FileName; } set { _FileName = value; } }
// return : // true : the file exist and we open it // false : the file doesn't exist and we create it public bool Open() { try { _xmlDocument.Load(_FileName); } catch (System.IO.FileNotFoundException) { //if file is not found, create a new xml file XmlTextWriter xmlWriter = new XmlTextWriter(_FileName, System.Text.Encoding.UTF8); xmlWriter.Formatting = Formatting.Indented; xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xmlWriter.WriteStartElement("Root"); //If WriteProcessingInstruction is used as above, //Do not use WriteEndElement() here //xmlWriter.WriteEndElement(); //it will cause the <Root></Root> to be <Root /> xmlWriter.Close(); _xmlDocument.Load(_FileName); return false; } return true; }
public CConfig(string strFileName) { FileName = strFileName; _xmlDocument = new XmlDocument(); this.Open(); }
~CConfig() { Save(); }
public void Save() { _xmlDocument.Save(_FileName); }
public string Get(string strName) { XmlNode node = _xmlDocument.SelectSingleNode("Root").SelectSingleNode(strName); if (node == null) { return "nonexist"; } else { return node.InnerText; } }
public void Set(string strName, string strValue) { XmlNode root = _xmlDocument.SelectSingleNode("Root"); XmlNode node = root.SelectSingleNode(strName);
if (node != null) { node.InnerText = strValue; } else { XmlElement elem = _xmlDocument.CreateElement(strName); elem.InnerText = strValue; root.AppendChild(elem); } }
二。使用示例:
创建访问XML配置文件的对象 CConfig Config = new CConfig("config.xml");
读取一个配置值 _IPAddress = Config.Get("IPAddress");
设置一个配置值并保存 Config.Set("IPAddress", _IPAddress); Config.Save();
三。评价:
跟XML相关的5个名字空间, 提供了一整套解决方案, 不过东西太多,初学比较繁琐。
用XML来管理配置信息比较方便。 比如设置一个配置信息: Config.Set("IPAddress", _IPAddress); 不用关心在文件中各个条目的先后顺序。 读取也是如此。 另外XML的纯文本特性便于用户直接修改配置文件。
配置信息多的时候,还可以多分几层, 比如<SystemConfig>下放跟系统有关的配置, <UserConfig>下放跟用户偏好有关的配置。
|