andrew4582

ReadStream

Mar 8th, 2012
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.32 KB | None | 0 0
  1. /// <summary>
  2.         /// Reads the entire request buffer to memory and return it as a byte array.
  3.         /// </summary>
  4.         /// <param name="stream">The stream to read.</param>
  5.         /// <returns>The returned byte array.</returns>
  6.         public static byte[] ReadData(this Stream stream) {
  7.             var list = new List<byte[]>();
  8.             const int defaultBufferSize = 1024 * 16;
  9.             var buffer = new byte[defaultBufferSize];
  10.             var currentOffset = 0;
  11.             int read;
  12.             while((read = stream.Read(buffer,currentOffset,buffer.Length - currentOffset)) != 0) {
  13.                 currentOffset += read;
  14.                 if(currentOffset == buffer.Length) {
  15.                     list.Add(buffer);
  16.                     buffer = new byte[defaultBufferSize];
  17.                     currentOffset = 0;
  18.                 }
  19.             }
  20.             var totalSize = list.Sum(x => x.Length) + currentOffset;
  21.             var result = new byte[totalSize];
  22.             var resultOffset = 0;
  23.             foreach(var partial in list) {
  24.                 Buffer.BlockCopy(partial,0,result,resultOffset,partial.Length);
  25.                 resultOffset += partial.Length;
  26.             }
  27.             Buffer.BlockCopy(buffer,0,result,resultOffset,currentOffset);
  28.             return result;
  29.         }
  30.     }
Add Comment
Please, Sign In to add comment