To convert Stream to ByteArray in C# and VB.NET you can use the following snippet.

Samples

Sample C#

public static byte[] StreamToByteArray(Stream inputStream)
{
	byte[] bytes = new byte[16384];
	using (MemoryStream memoryStream = new MemoryStream())
	{
		int count;
		while ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
		{
			memoryStream.Write(bytes, 0, count);
		}
		return memoryStream.ToArray();
	}
}

Sample VB.NET

Public Function StreamToByteArray(inputStream As Stream) As Byte()
	Dim bytes = New Byte(16383) {}
	Using memoryStream = New MemoryStream()
		Dim count As Integer
		While ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
			memoryStream.Write(bytes, 0, count)
		End While
		Return memoryStream.ToArray()
	End Using
End Function

Compatibility: working .NET 2.0 working .NET 3.0 not tested .NET 3.5 not working .NET 4.0 not working .NET 4.5not working .NET 4.6

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

6 thought on “How to convert Stream to ByteArray in C# and VB.NET”

Leave a Reply