C#中讀寫檔案主要涉及到File,FileInfo,FileStream三個類,它們都是System.IO 的類,StreamReader是用於從流讀取和寫入流的類,使用之前都需using System.IO。
先定義一個TXT文檔路徑: string txtpath = (@"D:\url\livebaby.cn.txt") 要讀入這個文檔。
1)File 提供用於建立、複製、刪除、移動和開啟檔案的靜態方法,並協助建立 FileStream。
FileStream fs = File.Open(txtpath, FileMode.Open);
File可以直接調用各種方法(Open、Delete、Exists等)
例如: if (File.Exists(txtpath))
{
File.Delete(txtpath);
}
2)FileInfo 提供用於建立、複製、刪除、移動和開啟檔案的執行個體方法,並協助建立 FileStream。
FileInfo fi = new FileInfo(txtpath); //執行個體化
FileStream fs = fi.Open();
3)FileStream 支援通過其 Seek 方法隨機訪問檔案。預設情況下,FileStream 以同步方式開啟檔案,但它也支援非同步作業。
利用FileStream 我們可以得到一個檔案的Streams,接著就是來讀取。
(4)StreamReader 通過使用 Encoding 進行字元和位元組的轉換,從 Streams 中讀取字元。
StreamWriter 通過使用 Encoding 將字元轉換為位元組,向 Streams 寫入字元。
StreamReader sr = new StreamReader(fs);
string str = null;
string temp=null;
while((temp=sr.ReadLine())!=null)
{
str+=" "+temp;
}
得到一個字串,再可以對字串進行處理。
TextReader 是 StreamReader 和 StringReader 的抽象基類。抽象 Stream 類的實現用於位元組輸入和輸出,而 TextReader 的實現用於 Unicode 字元輸出。
TextWriter 是 StreamWriter 和 StringWriter 的抽象基類。抽象 Stream 類的實現用於位元組輸入和輸出,而 TextWriter 的實現用於 Unicode 字元輸出。