How to convert an Stream into a byte[] in C#? [duplicate] How to convert an Stream into a byte[] in C#? [duplicate] arrays arrays

How to convert an Stream into a byte[] in C#? [duplicate]


The shortest solution I know:

using(var memoryStream = new MemoryStream()){  sourceStream.CopyTo(memoryStream);  return memoryStream.ToArray();}


Call next function like

byte[] m_Bytes = StreamHelper.ReadToEnd (mystream);

Function:

public static byte[] ReadToEnd(System.IO.Stream stream){    long originalPosition = 0;    if(stream.CanSeek)    {         originalPosition = stream.Position;         stream.Position = 0;    }    try    {        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;    }    finally    {        if(stream.CanSeek)        {             stream.Position = originalPosition;         }    }}


In .NET Framework 4 and later, the Stream class has a built-in CopyTo method that you can use.

For earlier versions of the framework, the handy helper function to have is:

public static void CopyStream(Stream input, Stream output){    byte[] b = new byte[32768];    int r;    while ((r = input.Read(b, 0, b.Length)) > 0)        output.Write(b, 0, r);}

Then use one of the above methods to copy to a MemoryStream and call GetBuffer on it:

var file = new FileStream("c:\\foo.txt", FileMode.Open);var mem = new MemoryStream();// If using .NET 4 or later:file.CopyTo(mem);// Otherwise:CopyStream(file, mem);// getting the internal buffer (no additional copying)byte[] buffer = mem.GetBuffer();long length = mem.Length; // the actual length of the data                           // (the array may be longer)// if you need the array to be exactly as long as the databyte[] truncated = mem.ToArray(); // makes another copy

Edit: originally I suggested using Jason's answer for a Stream that supports the Length property. But it had a flaw because it assumed that the Stream would return all its contents in a single Read, which is not necessarily true (not for a Socket, for example.) I don't know if there is an example of a Stream implementation in the BCL that does support Length but might return the data in shorter chunks than you request, but as anyone can inherit Stream this could easily be the case.

It's probably simpler for most cases to use the above general solution, but supposing you did want to read directly into an array that is bigEnough:

byte[] b = new byte[bigEnough];int r, offset;while ((r = input.Read(b, offset, b.Length - offset)) > 0)    offset += r;

That is, repeatedly call Read and move the position you will be storing the data at.