What is the prefered method for creating a byte array from an input stream?
Here is my current solution with .NET 3.5.
Stream s;
byte[] b;
using (
i was able to make it work on a single line:
byte [] byteArr= ((MemoryStream)localStream).ToArray();
as clarified by johnnyRose, Above code will only work for MemoryStream
Just want to point out that in case you have a MemoryStream you already have memorystream.ToArray()
for that.
Also, if you are dealing with streams of unknown or different subtypes and you can receive a MemoryStream
, you can relay on said method for those cases and still use the accepted answer for the others, like this:
public static byte[] StreamToByteArray(Stream stream)
{
if (stream is MemoryStream)
{
return ((MemoryStream)stream).ToArray();
}
else
{
// Jon Skeet's accepted answer
return ReadFully(stream);
}
}
You can use this extension method.
public static class StreamExtensions
{
public static byte[] ToByteArray(this Stream stream)
{
var bytes = new List<byte>();
int b;
while ((b = stream.ReadByte()) != -1)
bytes.Add((byte)b);
return bytes.ToArray();
}
}
This is the function which I am using, tested and worked well. please bear in mind that 'input' should not be null and 'input.position' should reset to '0' before reading otherwise it will break the read loop and nothing will read to convert to array.
public static byte[] StreamToByteArray(Stream input)
{
if (input == null)
return null;
byte[] buffer = new byte[16 * 1024];
input.Position = 0;
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
byte[] temp = ms.ToArray();
return temp;
}
}