C#讀寫txt檔案的兩種方法介紹
阿新 • • 發佈:2018-12-09
1.新增名稱空間
System.IO;
System.Text;
2.檔案的讀取
(1).使用FileStream類進行檔案的讀取,並將它轉換成char陣列,然後輸出。
byte[] byData = new byte[100]; char[] charData = new char[1000]; public void Read() { try { FileStream file = new FileStream("E:\\test.txt", FileMode.Open); file.Seek(0, SeekOrigin.Begin); file.Read(byData, 0, 100); //byData傳進來的位元組陣列,用以接受FileStream物件中的資料,第2個引數是位元組陣列中開始寫入資料的位置,它通常是0,表示從陣列的開端檔案中向陣列寫資料,最後一個引數規定從檔案讀多少字元. Decoder d = Encoding.Default.GetDecoder(); d.GetChars(byData, 0, byData.Length, charData, 0); Console.WriteLine(charData); file.Close(); } catch (IOException e) { Console.WriteLine(e.ToString()); } }
(2).使用StreamReader讀取檔案,然後一行一行的輸出。
public void Read(string path) { StreamReader sr = new StreamReader(path,Encoding.Default); String line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line.ToString()); } }
3.檔案的寫入
(1).使用FileStream類建立檔案,然後將資料寫入到檔案裡。
public void Write() { FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create); //獲得位元組陣列 byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!"); //開始寫入 fs.Write(data, 0, data.Length); //清空緩衝區、關閉流 fs.Flush(); fs.Close(); }
(2).使用FileStream類建立檔案,使用StreamWriter類,將資料寫入到檔案。
public void Write(string path) { FileStream fs = new FileStream(path, FileMode.Create); StreamWriter sw = new StreamWriter(fs); //開始寫入 sw.Write("Hello World!!!!"); //清空緩衝區 sw.Flush(); //關閉流 sw.Close(); fs.Close(); }
以上就完成了,txt文字文件的資料讀取與寫入。