我正在尝试将从 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,使其无效。如何获得它的正确字节数组?
最佳答案
如果要从内存流中读取,需要确保流的当前位置在开头。
此外,您使用的 Read
方法是错误的。它返回读取的字节数,该数可能小于请求的字节数。要正确使用它,您需要循环直到获得流中的所有字节。
但是,您应该只使用 ToArray
方法将流中的所有内容作为字节数组获取:
Private Function GetStreamAsByteArray(ByVal stream As MemoryStream) As Byte()
Return stream.ToArray()
End Function
关于vb.net - 在 VB.Net 中将 MemoryStream 转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22804224/