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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22804224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:17:06  来源:igfitidea点击:

Converting MemoryStream to Byte Array in VB.Net

vb.netsilverlightbytearrayrichedit-control

提问by Anish

I am trying to convert the memory stream generated from richeditDocument to byte array. The code is given below:

我正在尝试将从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

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?

生成流是因为我可以获得流长度,但是最终的位数组仅由 0 组成,使其无效。我怎样才能得到它的正确字节数组?

回答by Guffa

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 Readmethod 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.

另外,您使用的Read方法错误。它返回读取的字节数,可能小于请求的字节数。要正确使用它,您需要循环直到获得流中的所有字节。

However, you should just use the ToArraymethod to get everything in the stream as a byte array:

但是,您应该只使用该ToArray方法将流中的所有内容作为字节数组获取:

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

  Return stream.ToArray()

End Function

回答by IRSH

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

'这对我有用 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