Иногда приходят потоки, и вы не знаете, насколько они велики, для этого используйте следующий код:
public static byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = stream.Position;
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
Затем, получив массив байтов, вы можете преобразовать его в поток памяти ...
byte[] myBytes = ReadToEnd(theStream);
Stream theMemStream = new MemoryStream(myBytes, 0, myBytes.Length);