備份存儲區是一個存儲媒介,例如磁盤或內存。 每一個不一樣的備份存儲區都實現其本身的流做爲 Stream 類的實現。 每一個流類型也都從其給定的備份存儲區讀取字節並向其給定的備份存儲區寫入字節。 鏈接到備份存儲區的流叫作基流。 基流具備的構造函數具備將流鏈接到備份存儲區所需的參數。 例如,FileStream 具備指定路徑參數(指定進程將如何共享文件的參數)等的構造函數。數組
System.IO 類的設計提供簡化的流構成。 能夠將基流附加到一個或多個提供所需功能的傳遞流。 讀取器或編寫器能夠附加到鏈的末端,這樣即可以方便地讀取或寫入所需的類型。ide
下面的代碼示例圍繞現有 MyFile.txt 建立 FileStream,爲 MyFile.txt 提供緩衝。 (請注意,默認狀況下緩衝 FileStreams。)而後,建立 StreamReader 以讀取 FileStream 中的字符,FileStream 將做爲 StreamReader 的構造函數參數傳遞給它。 ReadLine 將進行讀取,直到 Peek 再也找不到任何字符爲止。函數
using System; using System.IO; public class CompBuf { private const string FILE_NAME = "MyFile.txt"; public static void Main() { if (!File.Exists(FILE_NAME)) { Console.WriteLine("{0} does not exist!", FILE_NAME); return; } FileStream fsIn = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read, FileShare.Read); // Create an instance of StreamReader that can read // characters from the FileStream. using (StreamReader sr = new StreamReader(fsIn)) { string input; // While not at the end of the file, read lines from the file. while (sr.Peek() > -1) { input = sr.ReadLine(); Console.WriteLine(input); } } } }
下面的代碼示例圍繞現有 MyFile.txt 建立 FileStream,爲 MyFile.txt 提供緩衝。 (請注意,默認狀況下緩衝 FileStreams。)而後,建立 BinaryReader 以讀取 FileStream 中的字節,FileStream 將做爲 BinaryReader 的構造函數參數傳遞給它。 ReadByte 將進行讀取,直到 PeekChar 再也找不到任何字節爲止。ui
using System; using System.IO; public class ReadBuf { private const string FILE_NAME = "MyFile.txt"; public static void Main() { if (!File.Exists(FILE_NAME)) { Console.WriteLine("{0} does not exist.", FILE_NAME); return; } FileStream f = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read, FileShare.Read); // Create an instance of BinaryReader that can // read bytes from the FileStream. using (BinaryReader br = new BinaryReader(f)) { byte input; // While not at the end of the file, read lines from the file. while (br.PeekChar() > -1 ) { input = br.ReadByte(); Console.WriteLine(input); } } } }