This code fragment helpfully loads a file (or any stream) into a MemoryStream. It does it by repeatedly reading data into a buffer and adding this to the stream.
As an optimisation, if the stream support seeking the the memory stream is created with the same capacity. This means that its internal buffer does not need to be grown during the load.
Be careful: This code will allocate enough memory to load the entire contents of a file (or other stream). If you open a huge file, it will steal all you memory and possible thrash your disks trying to use virtual memory.
' open a file stream for reading, and load into a memory stream
Public Function StreamToMemory(ByVal path As String) As MemoryStream
Dim input As FileStream
Dim output As MemoryStream
input = New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)
output = StreamToMemory(input)
input.Close()
Return output
End Function
' transfer contents of input stream to memory stream
Public Function StreamToMemory(ByVal input As Stream) As IO.MemoryStream
Dim buffer(1023) As Byte
Dim count As Integer = 1024
Dim output As MemoryStream
' build a new stream
If input.CanSeek Then
output = New MemoryStream(input.Length)
Else
output = New MemoryStream
End If
' iterate stream and transfer to memory stream
Do
count = input.Read(buffer, 0, count)
If count = 0 Then Exit Do
output.Write(buffer, 0, count)
Loop
' rewind stream
output.Position = 0
' pass back
Return output
End Function


