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 (
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);
}
}