1. 程式人生 > >WINCE C#讀寫INI檔案

WINCE C#讀寫INI檔案

最近開發一個CE上的GPS程式,用到配置儲存,由於資料比較少且資料結構簡單,所以採用了INI格式,WINCE沒有提供windows裡讀寫ini的函式,就自己寫了一個,程式碼如下(C#):

    //////////////////////////////////////////////////////////////////////////
    //ini檔案的C#讀寫
    //鍾磊 [email protected]
    //20090714   
    class ZL_INI
    {
        /************************************************************************/
        /*寫操作
         * strSection   節
         * strKey       鍵
         * strValue     需要寫入的值
         * strFilePath  配置檔案的全路徑(wince中只能使用絕對全路徑)
         */
        /************************************************************************/
       
        public static void PutINI(string strSection, string strKey, string strValue, string strFilePath)
        {
            INICommon(false, strSection, strKey, strValue, strFilePath);
        }

        /************************************************************************/
        /* 讀操作
         * strSection   節
         * strKey       鍵
         * strDefault   如果未找到相應鍵對應的值則填入此值
         * strFilePath  配置檔案的全路徑(wince中只能使用絕對全路徑)
         * 返回:       指定鍵的相應值
         * 說明:       如果在檔案中未找到相應節則新增,未找到相應鍵亦新增,如果鍵對應的值為空串則使用預設值填充ini檔案並返回
        /************************************************************************/

        public static string GetINI(string strSection, string strKey, string strDefault, string strFilePath)
        {
            return INICommon(true, strSection, strKey, strDefault, strFilePath);
        }

        private static string[] Split(string input, string pattern)
        {
            string[] arr = System.Text.RegularExpressions.Regex.Split(input, pattern);
            return arr;
        }
        private static void AppendToFile(string strPath, string strContent)
        {
            FileStream fs = new FileStream(strPath, FileMode.Append);
            StreamWriter streamWriter = new StreamWriter(fs, System.Text.Encoding.Default);
            streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            streamWriter.WriteLine(strContent);
            streamWriter.Flush();
            streamWriter.Close();
            fs.Close();
        }
        private static void WriteArray(string strPath, string[] strContent)
        {
            FileStream fs = new FileStream(strPath, FileMode.Truncate);
            StreamWriter streamWriter = new StreamWriter(fs, System.Text.Encoding.Default);
            streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);

            for (int i = 0; i < strContent.Length; i++)
            {
                if (strContent[i].Trim() == "/r/n")
                    continue;
                streamWriter.WriteLine(strContent[i].Trim());
            }

            streamWriter.Flush();
            streamWriter.Close();
            fs.Close();
        }               
        //INI解析
        private static string INICommon(bool isRead, string ApplicationName, string KeyName, string Default, string FileName)
        {
            string strSection = "[" + ApplicationName + "]";
            string strBuf;
            try
            {
                //a.檔案不存在則建立
                if (!File.Exists(FileName))
                {
                    FileStream sr = File.Create(FileName);
                    sr.Close();
                }
                //讀取INI檔案
                System.IO.StreamReader stream = new System.IO.StreamReader(FileName, System.Text.Encoding.Default);
                strBuf = stream.ReadToEnd();
                stream.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "INI檔案讀取異常");
                return Default;
            }

            string[] rows = Split(strBuf, "/r/n");
            string oneRow;
            int i = 0;
            for (; i < rows.Length; i++)
            {
                oneRow = rows[i].Trim();

                //空行
                if (0 == oneRow.Length)
                    continue;

                //此行為註釋
                if (';' == oneRow[0])
                    continue;

                //沒找到
                if (strSection != oneRow)
                    continue;

                //找到了
                break;
            }

            //b.沒找到對應的section,建立一節並建立屬性
            if (i >= rows.Length)
            {
                AppendToFile(FileName, "/r/n" + strSection + "/r/n" + KeyName + "=" + Default);
                return Default;
            }

            //找到section

            i += 1; //跳過section 

            int bakIdxSection = i;//備份section的下一行

            string[] strLeft;

            //查詢屬性
            for (; i < rows.Length; i++)
            {
                oneRow = rows[i].Trim();

                //空行
                if (0 == oneRow.Length)
                    continue;

                //此行為註釋
                if (';' == oneRow[0])
                    continue;

                //越界
                if ('[' == oneRow[0])
                    break;

                strLeft = Split(oneRow, "=");

                if (strLeft == null || strLeft.Length != 2)
                    continue;

                //找到屬性
                if (strLeft[0].Trim() == KeyName)
                {
                    //讀
                    if (isRead)
                    {
                        //c.找到屬性但沒有值
                        if (0 == strLeft[1].Trim().Length)
                        {
                            rows[i] = strLeft[0].Trim() + "=" + Default;
                            WriteArray(FileName, rows);
                            return Default;
                        }
                        else
                        {
                            //找到了                       
                            return strLeft[1].Trim();
                        }
                    }

                    //寫
                    else
                    {
                        rows[i] = strLeft[0].Trim() + "=" + Default;
                        WriteArray(FileName, rows);
                        return Default;
                    }
                }
            }

            //d.沒找到對應的屬性,建立之並賦為預設
            rows[bakIdxSection] = rows[bakIdxSection] + "/r/n" + KeyName + "=" + Default;
            WriteArray(FileName, rows);
            return Default;
        }
    }