標籤:
/// <summary> /// 不調用系統API 讀寫 ini 設定檔 /// </summary> public class RW_ini { #region ========ini 讀寫======== // 首次調用 RWini 時需要初始化此參數 public static string pathIni; // 記錄錯誤資訊 與 WriteLog 一起使用 public static string pathErr; public static string ReadIni(string section, string key) { string result = ""; try { // 檔案不存在則建立 if (!File.Exists(pathIni)) { File.Create(pathIni); } else { //讀取INI檔案 string buffer; string[] temp; using (StreamReader sr = new StreamReader(pathIni, Encoding.Default)) { while (sr.Peek() >= 0) { buffer = sr.ReadLine().Trim(); if (!string.IsNullOrEmpty(buffer) && buffer.StartsWith(string.Format("[{0}]", section), StringComparison.OrdinalIgnoreCase)) { while (sr.Peek() > 0) { buffer = sr.ReadLine().Trim(); if (!string.IsNullOrEmpty(buffer)) { if (buffer.StartsWith("[")) break; if (!buffer.StartsWith(";")) { temp = buffer.Split(‘=‘); if (temp.Length > 1 && temp[0].TrimEnd().Equals(key, StringComparison.OrdinalIgnoreCase)) { return temp[1].TrimStart(); } } } } // 不再判斷下一個節點 return result; } } } } // 不再判斷下一個節點 return result; } catch { throw new ApplicationException("同步檔案讀取異常!"); } } private void WriteIni(string section, string key, string value) { try { // 檔案不存在則建立 if (!File.Exists(pathIni)) { File.Create(pathIni); } // 修改INI檔案 bool modify = false, find = false; string buffer; List<string> temp = new List<string>(); // 將所有設定檔放到集合中 using (StreamReader sr = new StreamReader(pathIni, Encoding.Default)) { while (sr.Peek() >= 0) { buffer = sr.ReadLine().Trim(); temp.Add(buffer); if (!modify && !string.IsNullOrEmpty(buffer) && buffer.StartsWith(string.Format("[{0}]", section), StringComparison.OrdinalIgnoreCase)) { find = true; while (sr.Peek() >= 0) { buffer = sr.ReadLine().Trim(); temp.Add(buffer); if (!string.IsNullOrEmpty(buffer)) { if (buffer.StartsWith("[")) break; if (!modify && !buffer.StartsWith(";") && buffer.Split(‘=‘)[0].TrimEnd() == key) { modify = true; temp.RemoveAt(temp.Count - 1); if (value != null) { temp.Add(string.Format("{0} = {1}", key, value)); } } } } if (!modify) { temp.Insert(temp.Count - 1, string.Format("{0} = {1}", key, value)); } } } if (!modify && !find) { temp.Add(string.Format("[{0}]", section)); temp.Add(string.Format("{0} = {1}", key, value)); } } using (StreamWriter sw = new StreamWriter(pathIni, false, Encoding.Default)) { foreach (string item in temp) sw.WriteLine(item); } } catch { throw new ApplicationException("同步檔案寫入異常!"); } } public static void WriteLog(string content) { File.AppendText(pathErr).WriteLine("時間:{0} 資訊:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm"), content); } }
因為 WinCE 不帶讀寫 ini 的API 而且自己用的設定檔節點並不多
因此自己編寫此類 用於 WinCE 系統中。C# 代碼
自己寫的 讀寫 ini 設定檔類