.NET Copy Stream to Stream and dump stream to file

By Allen Stoner

There are lots of occasions when a programmer may want to copy the contents of one stream to another stream. This may be from one memory stream to another memory stream, or a memory stream to a file stream. Here are two general routines to assist with doing that.

  Private Sub DumpStream(ByVal outStream As Stream, ByVal outputFileName As String)
    ' Dump the contents of a stream to a file
    outStream.Flush()
    Dim SavePos As Long = outStream.Position        ' Save the original position in the stream
    outStream.Seek(0, SeekOrigin.Begin)
    Dim f As Stream = File.OpenWrite(outputFileName)
    CopyStream(outStream, f)
     outStream.Position = SavePos                     '  Go back to the original postion in the stream
    f.Close()
  End Sub

  Public Shared Sub CopyStream(ByVal input As Stream, ByVal output As Stream)
    ' Copy the contents of one stream to another stream
    Dim buf As Byte() = New Byte(8 * 1024 - 1) {}      '  A buffer for storing data while copying
    Dim len As Integer
    len = input.Read(buf, 0, buf.Length)
    While len > 0
      output.Write(buf, 0, len)
      len = input.Read(buf, 0, buf.Length)
    End While
  End Sub

.NET Copy Stream to Stream and dump stream to file  (2003 Views)