當在派生類中重寫時,從當前流讀取字節序列,並將此流中的位置提升讀取的字節數。
程序集: mscorlib(mscorlib.dll 中)
public: virtual int Read( array<unsigned char>^ buffer, int offset, int count ) abstract
參數
- buffer
-
字節數組。此方法返回時,該緩衝區包含指定的字符數組,該數組的 offset 和 (offset + count -1) 之間的值由從當前源中讀取的字節替換。
- offset
-
buffer 中的從零開始的字節偏移量,從此處開始存儲從當前流中讀取的數據。
- count
-
要從當前流中最多讀取的字節數。
Exception | Condition |
---|---|
ArgumentException |
offset 與 count 的和大於緩衝區長度。 |
ArgumentNullException |
buffer 爲 null。 |
ArgumentOutOfRangeException |
offset 或 count 爲負。 |
IOException |
發生 I/O 錯誤。 |
NotSupportedException |
流不支持讀取。 |
ObjectDisposedException |
在流關閉後調用方法。 |
使用 CanRead 屬性來確定當前實例是否支持讀取。使用 ReadAsync 方法以從當前流中以異步方式讀取。
此方法的實現讀取的最多 count 從當前的字節流,並將其在存儲 buffer 開始的位置 offset。流中的當前位置高級讀取 ; 的字節數但是,如果發生異常,該流中的當前位置保持不變。實現返回讀取的字節數。該實現將阻止直到至少一個字節的數據可供讀取的事件中任何數據都可用。 Read只有當在流中沒有更多數據,並且沒有更多預期 (如套接字已關閉或文件結尾),則返回 0。實現可以自由地返回少於所請求的字節,即使尚未達到流的末尾。
使用 BinaryReader 用於讀取基元數據類型。
下面的示例演示如何使用 Read 要讀取的數據塊。
using namespace System; using namespace System::IO; public ref class Block { public: static void Main() { Stream^ s = gcnew MemoryStream(); for (int i = 0; i < 100; i++) { s->WriteByte((Byte)i); } s->Position = 0; // Now read s into a byte buffer. array<Byte>^ bytes = gcnew array<Byte>(s->Length); int numBytesToRead = (int) s->Length; int numBytesRead = 0; while (numBytesToRead > 0) { // Read may return anything from 0 to 10. int n = s->Read(bytes, numBytesRead, 10); // The end of the file is reached. if (n == 0) { break; } numBytesRead += n; numBytesToRead -= n; } s->Close(); // numBytesToRead should be 0 now, and numBytesRead should // equal 100. Console::WriteLine("number of bytes read: {0:d}", numBytesRead); } }; int main() { Block::Main(); }