This code snippet copies the contents of one stream (from its current position) to another stream.
There is nothing clever about this code, it is just handy to have around.
It validates that the input stream and output stream support reading and writing.
It performs an iterative copy using a fixed size buffer.
This may not as be efficient as loading the whole lot into memory, but it is guaranteed to use a fixed amount of memory and therefore work on streams of any size.
There is nothing clever about this code, it is just handy to have around.
It validates that the input stream and output stream support reading and writing.
It performs an iterative copy using a fixed size buffer.
This may not as be efficient as loading the whole lot into memory, but it is guaranteed to use a fixed amount of memory and therefore work on streams of any size.
Public Sub CopyStreamContents(ByVal objInput As Stream, ByVal objOutput As Stream)
' assert these are the right kind of streams
If objInput Is Nothing Then Throw New ArgumentNullException("input")
If objOutput Is Nothing Then Throw New ArgumentNullException("output")
If Not objInput.CanRead Then Throw New ArgumentException("Input stream must support CanRead")
If Not objOutput.CanWrite Then Throw New ArgumentException("Output stream must support CanWrite")
' skip if the input stream is empty (if seeking is supported)
If objInput.CanSeek Then If objInput.Length = 0 Then Exit Sub
' allocate buffer (if all pre-conditions are met)
Dim buffer(1023) As Byte
Dim count As Integer = buffer.Length
' iterate read/writes between streams
Do
count = objInput.Read(buffer, 0, count)
If count = 0 Then Exit Do
objOutput.Write(buffer, 0, count)
Loop
End Sub
450 comments,
VB.Net, Wednesday, July 27, 2005 15:34


