索引器的妙用,读取配置文件

 public  class SysConfig
    {
        // Fields
        private static SysRead m_SysRead;

        // Methods
        public static string sValue(string sKey)
        {
            string sPath = AppDomain.CurrentDomain.BaseDirectory + @"Config";
            if (!Directory.Exists(sPath))
            {
                Directory.CreateDirectory(sPath);
            }
            string xmlFile = sPath + @"\Config.Xml";
            if (File.Exists(xmlFile))
            {
                m_SysRead = new SysRead(xmlFile);
                if (sKey == "Conn")
                {
                    return m_SysRead.sConnection;
                }
                return m_SysRead[sKey];
            }
            //MessageBox.Show("读配置文件失败", "提示", MessageBoxButtons.OK);
            return "";
        }
    }
    public  class SysRead
    {
        // Fields
        private XmlDocument m_xmlDoc;
        private string m_xmlFile;
        private static XmlNode m_xmlNode;

        // Methods
        public SysRead(string sXmlFile)
        {
            try
            {
                this.m_xmlFile = sXmlFile;
                this.m_xmlDoc = new XmlDocument();
                this.m_xmlDoc.Load(this.m_xmlFile);
                m_xmlNode = this.m_xmlDoc.SelectSingleNode("Config");
            }
            catch
            {
                //MessageBox.Show("配置文件中存在非法字符", "提示", MessageBoxButtons.OK);
            }
        }

        ~SysRead()
        {
            m_xmlNode = null;
            this.m_xmlDoc = null;
        }

        private static string getConnValue(string sKey)
        {
            try
            {
                string[] param = new string[2];
                param = sKey.Split(new char[] { '.' });
                XmlNodeList nodelist = m_xmlNode.ChildNodes;
                foreach (XmlElement xE in nodelist)
                {
                    if (xE.Name == param[0])
                    {
                        return xE.GetAttribute(param[1]);
                    }
                }
            }
            catch
            {
                return "";
            }
            return "";
        }

        // Properties
        public string this[string sKey]
        {
            get
            {
                return getConnValue(sKey);
            }
        }

        public string sConnection
        {
            get
            {
                return ("database=" + this["connect.DataBase"] + "; Server=" + this["connect.ServerIp"] + ";User ID=" + this["connect.Uid"] + ";Password=" + this["connect.Pw"] + ";Persist Security Info=True");
            }
        }
    }

posted @ 2008-12-31 16:49  韩冰冰  阅读(251)  评论(0编辑  收藏  举报