Read Stream to Byte array in CSharp

Description

The following code shows how to read Stream to Byte array.

Example


  // w  ww  .  jav  a 2  s  .  c o m

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;


public class FileUtils
{
    public static byte[] GetStreamBytes(Stream stream)
    {
        stream.Position = 0;
        byte[] readBuffer = new byte[2048];
        List<byte> outputBytes = new List<byte>();

        int offset = 0;

        while (true)
        {
            int bytesRead = stream.Read(readBuffer, 0, readBuffer.Length);

            if (bytesRead == 0)
            {
                break;
            }
            else if (bytesRead == readBuffer.Length)
            {
                outputBytes.AddRange(readBuffer);
            }
            else
            {
                byte[] tempBuf = new byte[bytesRead];

                Array.Copy(readBuffer, tempBuf, bytesRead);

                outputBytes.AddRange(tempBuf);

                break;
            }

            offset += bytesRead;
        }

        return outputBytes.ToArray();
    }

}




















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var