Stream::Read 方法 (array^, Int32, Int32)

Stream::Read 方法 (array<Byte>^, Int32, Int32)

.NET Framework (current version)
 

當在派生類中重寫時,從當前流讀取字節序列,並將此流中的位置提升讀取的字節數。

命名空間:   System.IO
程序集:  mscorlib(mscorlib.dll 中)

public:
virtual int Read(
	array<unsigned char>^ buffer,
	int offset,
	int count
) abstract

參數

buffer

字節數組。此方法返回時,該緩衝區包含指定的字符數組,該數組的 offset 和 (offset + count -1) 之間的值由從當前源中讀取的字節替換。

offset

buffer 中的從零開始的字節偏移量,從此處開始存儲從當前流中讀取的數據。

count

要從當前流中最多讀取的字節數。

返回值

Type: System::Int32

讀入緩衝區中的總字節數。如果很多字節當前不可用,則總字節數可能小於請求的字節數;如果已到達流結尾,則爲零 (0)。

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();
}

Universal Windows Platform
4.5 後可用
.NET Framework
1.1 後可用
Portable Class Library
受以下版本支持:portable .NET platforms
Silverlight
2.0 後可用
Windows Phone Silverlight
7.0 後可用
Windows Phone
8.1 後可用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章