📄 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 + -