- public static byte [] Read2Buffer (Stream stream, int BufferLen){
- // 如果指定的无效长度的缓冲区,则指定一个默认的长度作为缓存大小
- if (BufferLen < 1){
- BufferLen = 0x8000;
- }
- // 初始化一个缓存区
- byte [] buffer = new byte [BufferLen];
- int read=0;
- int block;
- // 每次从流中读取缓存大小的数据,知道读取完所有的流为止
- while ( (block = stream.Read(buffer,
read, buffer.Length-read)) > 0){- // 重新设定读取位置
- read += block;
- // 检查是否到达了缓存的边界,检查是否还有可以读取的信息
- if (read == buffer.Length){
- // 尝试读取一个字节
- int nextByte = stream.ReadByte();
- // 读取失败则说明读取完成可以返回结果
- if (nextByte==-1){
- return buffer;
- }
- // 调整数组大小准备继续读取
- byte [] newBuf = new byte [buffer.Length*2];
- Array.Copy(buffer, newBuf, buffer.Length);
- newBuf[read]=( byte )nextByte;
- buffer = newBuf; // buffer是一个引用(指针),
这里意在重新设定buffer指针指向一个更大的内存- read++;
- }
- }
- // 如果缓存太大则使用ret来收缩前面while读取的buffer,然后直接返回
- byte [] ret = new byte [read];
- Array.Copy(buffer, ret, read);
- return ret;
- }
转自:http://developer.51cto.com/art/200908/145675.htm
【C#】stream读取
最新推荐文章于 2025-01-13 19:48:10 发布