如何将VB.Net中的MemoryStream对象有效转换成字节数组?
- 内容介绍
- 文章标签
- 相关推荐
本文共计298个文字,预计阅读时间需要2分钟。
我尝试将您提供的文本进行简化修改,不超过100字:
将richEditControl1生成的内存流转换为字节数组。代码如下:vbPublic Sub saveAsTemplate_Click(sender As Object, e As EventArgs) Dim ms As MemoryStream=New MemoryStream() richEditControl1.SaveDoc(ms)End Sub
我试图将从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
本文共计298个文字,预计阅读时间需要2分钟。
我尝试将您提供的文本进行简化修改,不超过100字:
将richEditControl1生成的内存流转换为字节数组。代码如下:vbPublic Sub saveAsTemplate_Click(sender As Object, e As EventArgs) Dim ms As MemoryStream=New MemoryStream() richEditControl1.SaveDoc(ms)End Sub
我试图将从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

