一开始想用INI格式的配置文件,最后发现,不仅需要引用API函数,操作起来也不见得怎么的好用,还是自己写个吧,反正操作XML文件要方便的许多。
配置文件模型示例:
<?xml version="1.0" encoding="utf-8"?>
<appset>
<run>自启动</run>
<hide>不隐藏主机</hide>
<level>50</level>
<app>关闭状态</app>
<web>http://vwwv.web.officelive.com/Documents/Notice.htm</web>
</appset>
XML文件操作类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;//引入XML命名空间
using System.Collections;//引入数组空间
using System.IO;
namespace ControXML
{
public class ControXMLClass
{
public string XMLPath;
/// <summary>
/// 定义构造函数
/// </summary>
public ControXMLClass(string XPath)
{
XMLPath = XPath;
}
/// <summary>
/// 读取数据
/// </summary>
/// <param name="father"></param>
/// <param name="son"></param>
/// <returns></returns>
public string ReadXML(string father, string son)
{
if (ExistXMLFile())
{
string nodeValue = "";
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.Load(XMLPath);
XmlNode xn = XMLDoc.SelectSingleNode(father);
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xnf in xnl)
{
if (xnf.Name == son)
{
nodeValue = xnf.InnerText;
}
}
return nodeValue;
}
else
{
return null;
}
}
/// <summary>
/// 写入数据
/// </summary>
/// <param name="father"></param>
/// <param name="son"></param>
/// <param name="str"></param>
public void WriteXML(string father, string son, string str)
{
if (ExistXMLFile())
{
//如果存在文件
XmlDocument XMLDoc = new XmlDocument();
XMLDoc.Load(XMLPath);
XmlNode xn = XMLDoc.SelectSingleNode(father);
XmlNodeList xnl = xn.ChildNodes;
foreach (XmlNode xnf in xnl)
{
if (xnf.Name == son)
{
xnf.InnerText = str;
}
}
XMLDoc.Save(XMLPath);
}
}
/// <summary>
/// 删除文件
/// </summary>
public void DelFile()
{
File.Delete(XMLPath);
}
/// <summary>
/// 验证文件是否存在
/// </summary>
/// <returns>布尔值</returns>
public bool ExistXMLFile()
{
return File.Exists(XMLPath);
}
}
}