سؤال

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?

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

'This works for me with a 100mb .txt file

    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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top