索引器的妙用,讀取配置檔案

iDotNetSpace發表於2009-01-04
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");
            }
        }
    }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-526505/,如需轉載,請註明出處,否則將追究法律責任。

相關文章