【C#】stream读取

来源:互联网 发布:苹果数据漫游 编辑:程序博客网 时间:2024/05/22 08:00
  1. public static byte[] Read2Buffer (Stream stream, int BufferLen){  
  2.  // 如果指定的无效长度的缓冲区,则指定一个默认的长度作为缓存大小  
  3.  if (BufferLen < 1){  
  4.  BufferLen = 0x8000;  
  5.  }  
  6.  // 初始化一个缓存区  
  7.  byte[] buffer = new byte[BufferLen];  
  8.  int read=0;   
  9.  int block;  
  10.  // 每次从流中读取缓存大小的数据,知道读取完所有的流为止  
  11.  while ( (block = stream.Read(buffer, 
    read, buffer.Length-read)) > 0){  
  12.  // 重新设定读取位置  
  13.  read += block;  
  14.    
  15.  // 检查是否到达了缓存的边界,检查是否还有可以读取的信息  
  16.  if (read == buffer.Length){  
  17.  // 尝试读取一个字节  
  18.  int nextByte = stream.ReadByte();  
  19.    
  20.  // 读取失败则说明读取完成可以返回结果  
  21.  if (nextByte==-1){  
  22.  return buffer;  
  23.  }  
  24.    
  25.  // 调整数组大小准备继续读取  
  26.  byte[] newBuf = new byte[buffer.Length*2];  
  27.  Array.Copy(buffer, newBuf, buffer.Length);  
  28.  newBuf[read]=(byte)nextByte;  
  29.  buffer = newBuf;// buffer是一个引用(指针),
    这里意在重新设定buffer指针指向一个更大的内存
     
  30.  read++;  
  31.  }  
  32.  }  
  33.  // 如果缓存太大则使用ret来收缩前面while读取的buffer,然后直接返回  
  34.  byte[] ret = new byte[read];  
  35.  Array.Copy(buffer, ret, read);  
  36.  return ret;  
  37. }

转自:http://developer.51cto.com/art/200908/145675.htm
原创粉丝点击