To copy one stream to another in C# and VB.NET you can use the following snippet.

Sample C#

//.NET 3.5
public static void CopyStream(Stream inputStream, Stream outputStream)
{
	var bytes = new byte[4096];
	int count;
	while ((count = inputStream.Read(bytes, 0, bytes.Length)) > 0)
	{
		outputStream.Write(bytes, 0, count);
	}
}

//.NET 4.0 +
public static void CopyStream(Stream inputStream, Stream outputStream)
{
	inputStream.CopyTo(outputStream, 4096);
}

//.NET 4.5+
 inputStream.CopyToAsync(outputStream, 4096);

Sample VB.NET

'.NET 3.5
Public Shared Sub CopyStream(inputStream As Stream, outputStream As Stream)
	Dim bytes = New Byte(4095) {}
	Dim count As Integer
	While (InlineAssignHelper(count, inputStream.Read(bytes, 0, bytes.Length))) > 0
		outputStream.Write(bytes, 0, count)
	End While
End Sub

'.NET 4.0 +
Public Shared Sub CopyStream(inputStream As Stream, outputStream As Stream)
	inputStream.CopyTo(outputStream, 4096)
End Sub

'.NET 4.5 +
inputStream.CopyToAsync(outputStream, 4096)

2 thought on “How to copy one stream to another in C# and VB.NET”

Leave a Reply