Convert stream to byte array - CSharp File IO

CSharp examples for File IO:Stream

Description

Convert stream to byte array

Demo Code


using System.Collections.Generic;
using System.IO;/* www.j av a2 s . c o  m*/
using System;

public class Main{
        /// <summary>
        /// Converte um objeto stream em byte array
        /// </summary>
        /// <param name="stream">Objeto stream a ser convertido</param>
        /// <returns>array de bytes</returns>
        public static byte[] ToByteArray(this 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)
                {
                    CopyBytes(stream, ref readBuffer, ref totalBytesRead, bytesRead);
                }


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

Related Tutorials