C#讀取和寫入文本文件
StreamReader和StreamWriter類用於讀取和寫入數據到文本文件。這些類從抽象基類流,支持讀取和寫入字節到一個文件流繼承。
StreamReader類
StreamReader類也繼承自抽象基類的TextReader表示讀者讀取一係列字符。下表描述了一些StreamReader類的常用方法:
S.N | 方法名稱及用途 |
---|---|
1 |
public override void Close() 它關閉StreamReader對象和基礎流,並釋放與讀者相關的所有係統資源 |
2 |
public override int Peek() 返回下一個可用字符,但並不使用它 |
3 |
public override int Read() 讀取從輸入流中的下一個字符,並通過一個字符前進的字符位置 |
例子:
下麵的例子演示了名為讀取Jamaica.txt的文本文件。文件內容如下:
Down the way where the nights are gay And the sun shines daily on the mountain top I took a trip on a sailing ship And when I reached Jamaica I made a stop
代碼如下:
using System; using System.IO; namespace FileApplication { class Program { static void Main(string[] args) { try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader("c:/jamaica.txt")) { string line; // Read and display lines from the file until // the end of the file is reached. while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { // Let the user know what went wrong. Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } Console.ReadKey(); } } }
猜猜當你編譯和運行程序是什麼顯示!
StreamWriter類
StreamWriter類繼承自抽象類TextWriter代表writer,可以寫入一係列字符。
下表顯示了一些此類的最常用的方法:
S.N | 方法名稱及用途 |
---|---|
1 |
public override void Close() 關閉當前StreamWriter對象和基礎流 |
2 |
public override void Flush() 清除所有緩衝區當前的writer ,並導致所有緩衝的數據寫入底層流 |
3 |
public virtual void Write(bool value) 寫一個布爾值的文本字符串或流的文本表示。 (繼承自TextWriter) |
4 |
public override void Write( char value ) 寫一個字符到流 |
5 |
public virtual void Write( decimal value ) 寫入十進製值的文本字符串或流的文本表示 |
6 |
public virtual void Write( double value ) 寫入8字節浮點值的文本串或流的文本表示 |
7 |
public virtual void Write( int value ) 寫一個4字節有符號整數的文本字符串或流的文本表示 |
8 |
public override void Write( string value ) 將一個字符串寫入流 |
9 |
public virtual void WriteLine() 寫入一個行結束的文本字符串或流 |
對於方法的完整列表,請訪問微軟的C#文檔。
例子:
下麵的例子演示了使用StreamWriter類將文本寫入數據到一個文件中:
using System; using System.IO; namespace FileApplication { class Program { static void Main(string[] args) { string[] names = new string[] {"Zara Ali", "Nuha Ali"}; using (StreamWriter sw = new StreamWriter("names.txt")) { foreach (string s in names) { sw.WriteLine(s); } } // Read and show each line from the file. string line = ""; using (StreamReader sr = new StreamReader("names.txt")) { while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } Console.ReadKey(); } } }
讓我們編譯和運行上麵的程序,這將產生以下結果:
Zara Ali Nuha Ali