Skip to content

Instantly share code, notes, and snippets.

@frankgeerlings
Created April 13, 2012 14:18
Show Gist options
  • Save frankgeerlings/2377205 to your computer and use it in GitHub Desktop.
Save frankgeerlings/2377205 to your computer and use it in GitHub Desktop.
Stream.ReadToEnd -- to convert stream to byte array
using System;
public static class StreamExtensions
{
// http://stackoverflow.com/questions/1080442/how-to-convert-an-stream-into-a-byte-in-c
public static byte[] ReadToEnd(this System.IO.Stream stream)
{
var originalPosition = stream.Position;
stream.Position = 0;
try
{
var readBuffer = new byte[4096];
var totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
var nextByte = stream.ReadByte();
if (nextByte != -1)
{
var temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
var buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
stream.Position = originalPosition;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment