c# wince 文本操作internal class TxtManager { private static string appPath = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString()); private static string dbSetTxtA = appPath + @"\DB_Set_A.ini"; //設定的文字檔 private static string dbSetTxtB = appPath + @"\DB_Set_B.ini"; //用來臨時儲存A中的內容 public string[,] readDBSetTxtA() //讀取文字檔 儲存到數組中 { StreamReader sr; FileStream fs = new FileStream(dbSetTxtA, FileMode.Open, FileAccess.Read); sr = new StreamReader(fs); string strLine = sr.ReadLine(); string[,] result = new string[10, 20]; int i = 0; while (strLine != null) // { //string _serial = ""; //string _sign = ""; //string _data = ""; //11 11 11 11 11 01 04 250 200 50 12 40 2.836226 16 50 0 1000 822.4379 1 20 //0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 string[] arrTxt = strLine.Split(' '); for (int j = 0; j < arrTxt.Length; j++) { result[i, j] = arrTxt[j]; } strLine = sr.ReadLine(); i++; } return result; } public void writeTxt(byte[] serial, byte[] sign, float[] data) //寫文字檔 如果關索引值 在數組文本中不存在 則將數組的內容寫到文本中 { string _serial = ""; string _sign = ""; string _data = ""; string _stringAll = ""; string _serial_sign = ""; for (int i = 0; i < serial.Length; i++) { _serial = _serial + " " + serial[i].ToString("X2"); } for (int i = 0; i < sign.Length; i++) { _sign = _sign + " " + sign[i].ToString("X2"); } for (int i = 0; i < data.Length; i++) { _data = _data + " " + data[i].ToString(); } _serial_sign = _serial.Trim() + " " + _sign.Trim(); _stringAll = _serial_sign + " " + _data.Trim(); StreamWriter sw; StreamReader sr; if (File.Exists(dbSetTxtA)) //文字檔存在 { //該處目的 將以前設定內容備份, //新寫入A中內容,之後讀取以前設定的內容,如果已經含有現寫入A中的裝置的設定,則B中的內容不匯入到A中 //保證A中每個裝置的設定都是最新的 File.Copy(dbSetTxtA, dbSetTxtB, true); sw = new StreamWriter(dbSetTxtA, false); //程式路徑下不存在文字檔,則 建立文字檔 sw.WriteLine(_stringAll.Trim()); //將設定內容寫到dbSetTxtA FileStream fs = new FileStream(dbSetTxtB, FileMode.Open, FileAccess.Read); sr = new StreamReader(fs); string strLine = sr.ReadLine(); while (strLine != null) // { // MessageBox.Show(strLine.Substring(0, _serial_sign.Length) + "\n" + _serial_sign); //如果B中的“地區值+" "+裝置值”在A剛寫入的內容中存在 說明該內容被更新 if (strLine.Substring(0, _serial_sign.Length) == _serial_sign) { //存在則不添加 } else { sw.WriteLine(strLine); } strLine = sr.ReadLine(); } sr.Close(); sw.Close(); File.Delete(dbSetTxtB); } else { sw = new StreamWriter(dbSetTxtA); //程式路徑下不存在文字檔,則 建立文字檔 sw.WriteLine(_stringAll.Trim()); sw.Close(); } } }
網上轉的,不錯