ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

ConvertToByteArray

Convert a Stream to an array of bytes.

Source

/// <summary>
/// This is a snippet by Chuhukon see:
/// http://www.koodr.com/item/e207aa7f-0ff1-4e8a-a703-e96f2f175bc9
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static byte[] ConvertToByteArray(this System.IO.Stream stream)
{
    var streamLength = Convert.ToInt32(stream.Length);
    byte[] data = new byte[streamLength + 1];

    //convert to to a byte array
    stream.Read(data, 0, streamLength);
    stream.Close();

    return data;
}

Example

FileStream f = File.OpenRead(@"c:\testfile.txt");
byte[] b = f.ConvertToByteArray();
Console.WriteLine(b.Length);

Author: Chuhukon

Submitted on: 13 feb 2011

Language: C#

Type: System.IO.Stream

Views: 5537