您的位置:首页 > 编程语言 > C#

C# 配置文件类

2015-06-26 11:42 393 查看
app.config多用于保存程序本身的配置,而用户配置用外部文件保存方便管理与修改

/// <summary>
/// 配置文件类
/// </summary>
public class ConfigHelper
{
/// <summary>
/// 获取外部配置文件对象(XML格式)
/// </summary>
/// <param myName="path">配置文件的完整路径
/// <returns>返回配置文件的HASHTABLE</returns>
public static Hashtable GetXmlSetting(string filePath)
{
Hashtable hash = new Hashtable();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
XmlNode businessnode = xmlDoc.SelectSingleNode("/UserConfig");
XmlNodeList list = businessnode.ChildNodes;
foreach (XmlNode node in list)
{
if (!node.Name.Equals("#comment"))
{
hash[node.Name] = node.InnerText;</span>
}
}
return hash;
}
}


引用示例:

配置文件内容:

<?xml version="1.0" encoding="utf-8" ?>
<UserConfig>
<ID>9527</ID>
<Name>小龙虾</Name>
<Other>Hello World!</Other>
</UserConfig>


string filePath1 = System.Web.HttpContext.Current.Server.MapPath("./" + "\\Config\\MyCfg.cfg")

string filePath2 = "C:\\MyCfg.cfg"

string strXmlRoot = "/UserConfig"

Hashtable config = ConfigHelper.GetXmlSetting(filePath, strXmlRoot);


打印内容:

Console.WriteLine(config["ID"].ToString());

Console.WriteLine(config["Name"].ToString());

Console.WriteLine(config["Other"].ToString());

/**************************************************
输出:

9527

小龙虾

Hello World!

***************************************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: