C# 配置文件类

app.config多用于保存程序本身的配置,而用户配置用外部文件保存方便管理与修改

    /// 
    /// 配置文件类
    /// 
    public class ConfigHelper
    {
        /// 
        /// 获取外部配置文件对象(XML格式)
        /// 
        /// 配置文件的完整路径
     /// 返回配置文件的HASHTABLE
     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;
                }
            }
            return hash;
        }
    }



引用示例:

配置文件内容:



  9527
  小龙虾
  Hello World!

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!

***************************************************/

你可能感兴趣的:(底层类库)