Stream
.
.
::
.Read 方法
更新:2007 年 11 月
当在派生类中重写时,从当前流读取字节序列,并将此流中的位置提升读取的字节数。
命名空间: System.IO
程序集: mscorlib(在 mscorlib.dll 中)
C#
|
public abstract int Read( byte[] buffer, int offset, int count ) |
参数
buffer
-
类型:
array<
System..::.Byte
>
[]
()
[]
字节数组。此方法返回时,该缓冲区包含指定的字符数组,该数组的 offset 和 (offset + count -1) 之间的值由从当前源中读取的字节替换。
-
offset
-
类型:
System..::.Int32
buffer 中的从零开始的字节偏移量,从此处开始存储从当前流中读取的数据。
-
count
-
类型:
System..::.Int32
要从当前流中最多读取的字节数。
返回值
类型: System..::.Int32读入缓冲区中的总字节数。如果当前可用的字节数没有请求的字节数那么多,则总字节数可能小于请求的字节数,或者如果已到达流的末尾,则为零 (0)。
此方法的实现从当前流中读取最多的 count 个字节,并将它们存储在从 offset 开始的 buffer 中。流中的当前位置提升已读取的字节数;但是,如果出现异常,流中的当前位置保持不变。实现返回已读取的字节数。仅当位置当前位于流的末尾时,返回值才为零。如果没有任何可用的数据,该实现将一直阻塞到至少有一个字节的数据可读为止。仅当流中不再有其他的数据,而且也不再需要更多的数据(如已关闭的套接字或文件尾)时,Read 才返回 0。即使尚未到达流的末尾,实现仍可以随意返回少于所请求的字节。
using System; using System.IO; public class Block { public static void Main() { Stream s = new MemoryStream(); for (int i=0; i<100; i++) s.WriteByte((byte)i); s.Position = 0; // Now read s into a byte buffer. byte[] bytes = new byte[s.Length]; int numBytesToRead = (int) s.Length; int numBytesRead = 0; while (numBytesToRead > 0) { // Read may return anything from 0 to numBytesToRead. int n = s.Read(bytes, numBytesRead, numBytesToRead); // 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: "+numBytesRead); } }