Convert MemoryStream to Byte Array in VB.Net

I am trying to convert a memory stream obtained from richeditDocument to an array of bytes. The code is 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 created as I can get the length of the stream, however the last bite array consists of only 0, which makes it invalid. How can I get the correct byte array?

+4
source share
2 answers

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

, Read . , . , , .

ToArray, :

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

  Return stream.ToArray()

End Function
+6

' 100mb.txt

    Public Function read()

    Dim tmpdb(0) As String

    Try

        tmpdb = IO.File.ReadAllLines("C:\Users\Admin01\Desktop\TmpTxt.txt")
        FileOpen(1, "C:\Users\Admin01\Desktop\IRSH_TEST_DB.jrdb", OpenMode.Binary, OpenAccess.Write)
        FilePut(1, tmpdb)
        FileClose(1)

        MessageBox.Show("SUCCES!")

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

End Function
0

Source: https://habr.com/ru/post/1534598/


All Articles