Stream to ByteArray c# , VB.Net

Creating a byte array from a stream

byte array from stream c# vb.net asp.net

Stream is the abstract base class of all streams and it Provides a generic view of a sequence of bytes. The Streams Object involve three fundamental operations such as Reading, Writing and Seeking. In some situations we may need to convert these stream to byte array. This lesson explain how to convert a stream to byteArray.

Convert byte array from stream


C# Source Code - Method 1
using System; using System.IO; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { FileStream stream1 = File.Open("D:\\file.txt", FileMode.Open); byte[] buff = streamToByteArray(stream1); stream1.Close(); MessageBox.Show(Encoding.UTF8.GetString(buff, 0, buff.Length)); } public static byte[] streamToByteArray(Stream stream) { byte[] byteArray = new byte[16 * 1024]; using (MemoryStream mSteram = new MemoryStream()) { int bit; while ((bit = stream.Read(byteArray, 0, byteArray.Length)) > 0) { mSteram.Write(byteArray, 0, bit); } return mSteram.ToArray(); } } } }

How to convert a byte array from Stream

byte array from Stream

This is the easiest method when comparing to first one.


C# Source Code - Method 2
using System; using System.IO; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { FileStream stream1 = File.Open("D:\\file.txt", FileMode.Open); byte[] buff = streamToByteArray(stream1); stream1.Close(); MessageBox.Show(Encoding.UTF8.GetString(buff, 0, buff.Length)); } public static byte[] streamToByteArray(Stream stream) { using (MemoryStream ms = new MemoryStream()) { stream.CopyTo(ms); return ms.ToArray(); } } } }

Convert byte array from stream - VB.Net Source Code

Imports System.IO Imports System.Text Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim stream1 As FileStream = File.Open("D:\file.txt", FileMode.Open) Dim buff As Byte() = streamToByteArray(stream1) stream1.Close() MsgBox(Encoding.UTF8.GetString(buff, 0, buff.Length)) End Sub Public Shared Function streamToByteArray(ByVal stream As Stream) As Byte() Using ms As New MemoryStream() stream.CopyTo(ms) Return ms.ToArray() End Using End Function End Class


NEXT.....Remove spaces from string