Tim Hastings - NonHostile (because there's no need)

Weblog and collection of geeky articles.

  Home :: Who? :: Contact :: Links :: Subscribe subscribe
The Quiet Before The Baby StormYay! Photo Booth!House For Sale... Sold


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

 



2 comments, VB.Net, Sunday, November 21, 2004 20:20

Timeline Navigation for VB.Net posts
VB.Net: Creating Functions with a variable Number of Parameters using ParamArray (made 2 weeks later)
VB.Net: Loading a File (or any other stream) into a Memory Stream (this post, made Sunday, November 21, 2004 20:20)
VB.Net: Convert DataTable to XML in An Unsophisticated Way (made 10 weeks earlier)


Comments
Brilliant. Thanks for this !!!!

Posted by: Darren on Friday, February 12, 2010 09:31

Post a Comment
Name:  Home page and email address are optional.
  Email addresses will not be displayed or spammed!
Remember these details
Email:
Home Page:
Comment:
Comments cannot contain HTML, URLs will be formatted into hyperlinks.
I reserve the right to remove any comments for any reason.