在VB.Net中将MemoryStream转换为Byte数组

6

我正在尝试将从richeditDocument生成的内存流转换为字节数组。以下是代码:

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

我可以获得流长度,因此生成了流,但最终的字节数组只包含0,使其无效。如何获取正确的字节数组?

2个回答

8
如果您想从内存流中读取内容,需要确保当前流的位置在开头。
此外,您错误地使用了“Read”方法。它返回已读取的字节数,这可能少于请求的字节数。要正确使用它,您需要循环直到获取流中的所有字节。
然而,您应该只需使用“ToArray”方法将流中的所有内容获取为一个字节数组:
Private Function GetStreamAsByteArray(ByVal stream As MemoryStream) As Byte()

  Return stream.ToArray()

End Function

0

这对我来说适用,使用了一个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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接