📄 xmlconfig.cs
字号:
using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Xml;
using System.Web;
using System.Collections;
using System.Collections.Specialized;
using System.Runtime.CompilerServices;
namespace qdog
{
/// <summary>
/// XML配置文件类
/// </summary>
/// <remarks>
/// <para>1. 多线程多实例读写安全。</para>
/// <para>2. 完成操作必须调用Dispose方法,建议使用using语句。</para>
/// <para>3. section、key名称不能以数字开头,且区分大小写。</para>
/// <para>4. 保存配置时,会调用对象ToString方法,对于非基元类型请重写该方法,以便能输出可用于保存数据的字符串。</para>
/// </remarks>
/// <example>
/// <code>
/// using(XmlConfig config = XmlConfig.Instance("setup.xml"))
/// {
/// config.Write("section", "key", "aaa");
/// Console.WriteLine(config.Read("section", "key"));
/// }
/// </code>
/// </example>
public class XmlConfig : System.IDisposable
{
private static Hashtable list;
private int count;
private string xmlfile;
private XmlDocument doc;
private XmlElement root;
private string m_strRoot;
/// <summary>
/// 静态构造
/// </summary>
static XmlConfig()
{
list = new Hashtable();
}
/// <summary>
/// 创建实例
/// </summary>
/// <param name="xmlfile">配置文件名</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.Synchronized)]
public static XmlConfig Instance(string xmlfile)
{
try
{
string fullName = new FileInfo(xmlfile).FullName;
XmlConfig config = (XmlConfig)list[fullName];
if (config == null)
{
config = new XmlConfig(xmlfile);
list[fullName] = config;
}
config.count++;
return config;
}
catch
{
throw new Exception("文件名不能为空!");
}
}
[MethodImpl(MethodImplOptions.Synchronized)]
public static XmlConfig Instance(string xmlfile, string strRoot)
{
try
{
string fullName = new FileInfo(xmlfile).FullName;
XmlConfig config = (XmlConfig)list[fullName];
if (config == null)
{
config = new XmlConfig(xmlfile, strRoot);
list[fullName] = config;
}
config.count++;
return config;
}
catch
{
throw new Exception("文件名不能为空!");
}
}
/// <summary>
/// 释放资源
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void Dispose()
{
if (--count <= 0)
{
string fullName = new FileInfo(xmlfile).FullName;
list.Remove(fullName);
}
}
public string RootName
{
get
{
if (m_strRoot == null)
return "config";
else
return m_strRoot;
}
set { m_strRoot = value; }
}
/// <summary>
/// 构造方法
/// </summary>
/// <param name="xmlfile">配置文件名</param>
private XmlConfig(string xmlfile)
{
this.xmlfile = xmlfile;
count = 0;
doc = new XmlDocument();
if (!File.Exists(xmlfile)) CreateConfigFile();
doc.Load(xmlfile);
root = doc.DocumentElement;
}
private XmlConfig(string xmlfile, string strRoot)
{
m_strRoot = strRoot;
this.xmlfile = xmlfile;
count = 0;
doc = new XmlDocument();
if (!File.Exists(xmlfile)) CreateConfigFile();
doc.Load(xmlfile);
root = doc.DocumentElement;
}
/// <summary>
/// 创建配置文件
/// </summary>
private void CreateConfigFile()
{
XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.AppendChild(declaration);
//XmlComment comment = doc.CreateComment("XML Config / Copyright (c) 2007");
//doc.AppendChild(comment);
//comment = doc.CreateComment(string.Format("Created Date {0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
//doc.AppendChild(comment);
XmlElement root = doc.CreateElement(RootName);
doc.AppendChild(root);
Save();
}
/// <summary>
/// Section
/// </summary>
private XmlNode GetSection(string name, bool create)
{
XmlNode node = root.SelectSingleNode(name);
if (create && node == null)
{
node = doc.CreateElement(name);
root.AppendChild(node);
}
return node;
}
/// <summary>
/// Key
/// </summary>
private XmlNode GetKey(string section, string key, bool create)
{
XmlNode sectionNode = GetSection(section, create);
if (sectionNode == null) return null;
XmlNode node = sectionNode.SelectSingleNode(key);
if (create && node == null)
{
node = doc.CreateElement(key);
sectionNode.AppendChild(node);
}
return node;
}
/// <summary>
/// 保存配置文件
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
private void Save()
{
doc.Save(xmlfile);
}
/// <summary>
/// 写入配置
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void Write(string section, string key, object value)
{
if (value == null) return;
section = section.Trim();//.ToLower();
key = key.Trim();//.ToLower();
XmlNode keyNode = GetKey(section, key, true);
keyNode.InnerText = value.ToString();
Save();
}
/// <summary>
/// 写入属性
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void WriteAttributes(string section, string key, StringDictionary attributes)
{
section = section.Trim();//.ToLower();
key = key.Trim();//.ToLower();
XmlNode keyNode = GetKey(section, key, true);
keyNode.Attributes.RemoveAll();
foreach (string name in attributes.Keys)
{
((XmlElement)keyNode).SetAttribute(name, attributes[name]);
}
Save();
}
/// <summary>
/// 写入属性
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void WriteAttribute(string section, string key, string attributeName, object value)
{
section = section.Trim();//.ToLower();
key = key.Trim();//.ToLower();
attributeName = attributeName.Trim();//.ToLower();
XmlNode keyNode = GetKey(section, key, true);
((XmlElement)keyNode).SetAttribute(attributeName, value.ToString());
Save();
}
/// <summary>
/// 读取配置
/// </summary>
public object Read(string section, string key)
{
section = section.Trim();//.ToLower();
key = key.Trim();//.ToLower();
XmlNode keyNode = GetKey(section, key, false);
if (keyNode == null)
return null;
else
return keyNode.InnerText;
}
/// <summary>
/// 读取属性
/// </summary>
public StringDictionary ReadAttributes(string section, string key)
{
section = section.Trim();//.ToLower();
key = key.Trim();//.ToLower();
StringDictionary sd = new StringDictionary();
XmlNode keyNode = GetKey(section, key, false);
if (keyNode == null) return sd;
foreach (XmlAttribute attribute in keyNode.Attributes)
{
sd.Add(attribute.Name, attribute.Value);
}
return sd;
}
/// <summary>
/// 读取属性
/// </summary>
public string ReadAttribute(string section, string key, string attributeName)
{
section = section.Trim();//.ToLower();
key = key.Trim();//.ToLower();
attributeName = attributeName.Trim();//.ToLower();
XmlNode keyNode = GetKey(section, key, false);
if (keyNode == null) return null;
return ((XmlElement)keyNode).GetAttribute(attributeName);
}
/// <summary>
/// 删除Section
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void DeleteSection(string section)
{
section = section.Trim();//.ToLower();
XmlNode sectionNode = GetSection(section, false);
if (sectionNode != null) root.RemoveChild(sectionNode);
Save();
}
/// <summary>
/// 删除Key
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void DeleteKey(string section, string key)
{
section = section.Trim();//.ToLower();
XmlNode sectionNode = GetSection(section, false);
XmlNode keyNode = GetKey(section, key, false);
if (keyNode != null) sectionNode.RemoveChild(keyNode);
Save();
}
/// <summary>
/// 清空所有配置
/// </summary>
[MethodImpl(MethodImplOptions.Synchronized)]
public void Clear()
{
root.RemoveAll();
Save();
}
/// <summary>
/// 获取所有Section
/// </summary>
public string[] Sections()
{
ArrayList list = new ArrayList();
for (int i = 0; i < root.ChildNodes.Count; i++)
{
if (!(root.ChildNodes[i] is XmlComment))
list.Add(root.ChildNodes[i].Name);
}
return (string[])list.ToArray(typeof(string));
}
/// <summary>
/// 获取所有Key
/// </summary>
public string[] Keys(string section)
{
XmlNode sectionNode = GetSection(section, false);
if (sectionNode == null) return new string[0];
ArrayList list = new ArrayList();
for (int i = 0; i < sectionNode.ChildNodes.Count; i++)
{
if (!(sectionNode.ChildNodes[i] is XmlComment))
list.Add(sectionNode.ChildNodes[i].Name);
}
return (string[])list.ToArray(typeof(string));
}
#region Overload Method
public int Read(string section, string key, int defaultValue)
{
object o = Read(section, key);
return o == null ? defaultValue : Convert.ToInt32(o);
}
public long Read(string section, string key, long defaultValue)
{
object o = Read(section, key);
return o == null ? defaultValue : Convert.ToInt64(o);
}
public string Read(string section, string key, string defaultValue)
{
object o = Read(section, key);
return o == null ? defaultValue : Convert.ToString(o);
}
public bool Read(string section, string key, bool defaultValue)
{
object o = Read(section, key);
return o == null ? defaultValue : Convert.ToBoolean(o);
}
public float Read(string section, string key, float defaultValue)
{
object o = Read(section, key);
return o == null ? defaultValue : Convert.ToSingle(o);
}
public double Read(string section, string key, double defaultValue)
{
object o = Read(section, key);
return o == null ? defaultValue : Convert.ToDouble(o);
}
public decimal Read(string section, string key, decimal defaultValue)
{
object o = Read(section, key);
return o == null ? defaultValue : Convert.ToDecimal(o);
}
public DateTime Read(string section, string key, DateTime defaultValue)
{
object o = Read(section, key);
return o == null ? defaultValue : Convert.ToDateTime(o);
}
public byte Read(string section, string key, byte defaultValue)
{
object o = Read(section, key);
return o == null ? defaultValue : Convert.ToByte(o);
}
public char Read(string section, string key, char defaultValue)
{
object o = Read(section, key);
return o == null ? defaultValue : Convert.ToChar(o);
}
#endregion
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -