Converting MemoryStream to Byte Array in VB.Net

Anish picture Anish · Apr 2, 2014 · Viewed 19.7k times · Source

I am trying to convert the memory stream generated from richeditDocument to byte array. The code is given below:

Public Sub saveAsTemplate_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    Dim ms As MemoryStream = New MemoryStream()
    richEditControl1.SaveDocument(ms, DocumentFormat.Rtf)
    GetStreamAsByteArray(ms)

    MessageBox.Show("save")

End Sub

Private Function GetStreamAsByteArray(ByVal stream As MemoryStream) As Byte()

    Dim streamLength As Integer = Convert.ToInt32(stream.Length)

    Dim fileData As Byte() = New Byte(streamLength) {}

    ' Read the file into a byte array
    stream.Read(fileData, 0, streamLength)
    stream.Flush()
    stream.Close()

    Return fileData

End Function

The stream is generated as I can get the stream length, however the final bite array only consist of 0's making it invalid. How can I get correct byte array of it?

Answer

Guffa picture Guffa · Apr 2, 2014

If you want to read from the memory stream, you need to make sure that the current position of the stream is at the beginning.

Also, you are using the Read method wrong. It returns the number of bytes read, which may be less than the number of bytes requested. To use it correctly you would need to loop until you have got all the bytes in the stream.

However, you should just use the ToArray method to get everything in the stream as a byte array:

Private Function GetStreamAsByteArray(ByVal stream As MemoryStream) As Byte()

  Return stream.ToArray()

End Function