?? comm_xml.cs
字號:
?using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
/// <summary>
/// xml 配置文件類
/// </summary>
public class Comm_Xml
{
private string FileName;
private string rootNode = "Setting";
#region 構造
public Comm_Xml(string sFileName)
{
FileName = sFileName;
//不存在創建
if (!File.Exists(sFileName))
{
XmlTextWriter xtw = new XmlTextWriter(sFileName, Encoding.UTF8);
xtw.Formatting = Formatting.Indented;
xtw.WriteStartDocument();
xtw.WriteStartElement(rootNode);
xtw.WriteEndElement();
xtw.WriteEndDocument();
xtw.Close();
}
}
#endregion
#region 寫配置
/// <summary>
/// 寫配置文件
/// </summary>
/// <param name="Section">主鍵</param>
/// <param name="Key">子鍵</param>
/// <param name="Value">寫入值</param>
public void WriteString(string Section, string Key, string Value)
{
bool bSectionExists = false;
bool bKeyExists = false;
XmlElement xe = null;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(FileName);
XmlNode root = xmldoc.SelectSingleNode(rootNode);
XmlNodeList rootlist = root.ChildNodes;
foreach (XmlNode xn in rootlist)
{
if (xn.Name == Section) //遍歷子節點
{
xe = (XmlElement)xn;
bSectionExists = true;
XmlNodeList subrootlist = xn.ChildNodes;
foreach (XmlNode xnsub in subrootlist)
{
if (xnsub.Name == Key)
{
xnsub.InnerText = Value;
bKeyExists = true;
break;
}
}
}
}
//父節點不存在處理
if (!bSectionExists)
{
xe = xmldoc.CreateElement(Section);
root.AppendChild(xe);
}
//子節點不存在處理
if (!bKeyExists)
{
XmlElement xe1 = xmldoc.CreateElement(Key);
xe1.InnerText = Value;
xe.AppendChild(xe1);
}
xmldoc.Save(FileName);
}
#endregion
#region 讀配置
/// <summary>
/// 讀配置文件
/// </summary>
/// <param name="Section">主鍵</param>
/// <param name="Key">子鍵</param>
/// <param name="DefaultValue">不存在默認返回值</param>
/// <returns>字符串值</returns>
public string ReadString(string Section, string Key, string DefaultValue)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(FileName);
XmlNode root = xmldoc.SelectSingleNode(rootNode);
XmlNodeList rootlist = root.ChildNodes;
foreach (XmlNode xn in rootlist)
{
if (xn.Name == Section) //遍歷子節點
{
XmlNodeList subrootlist = xn.ChildNodes;
foreach (XmlNode xnsub in subrootlist)
{
if (xnsub.Name == Key)
{
return xnsub.InnerText;
}
}
}
}
return DefaultValue;
}
#endregion
#region 刪除配置
/// <summary>
/// 刪除配置
/// </summary>
/// <param name="Section">主鍵</param>
/// <param name="Key">子鍵,為 null 時刪除主鍵</param>
public void DelKey(string Section, string Key)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(FileName);
XmlNode root = xmldoc.SelectSingleNode(rootNode);
XmlNodeList rootlist = root.ChildNodes;
foreach (XmlNode xn in rootlist)
{
if (xn.Name == Section) //遍歷子節點
{
if (Key == null) //整個主鍵刪除
{
root.RemoveChild(xn);
break;;
}
XmlNodeList subrootlist = xn.ChildNodes;
foreach (XmlNode xnsub in subrootlist)
{
if (xnsub.Name == Key)
{
xn.RemoveChild(xnsub);
break;
}
}
}
}
xmldoc.Save(FileName);
}
#endregion
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -