vb.net 从流生成字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22802119/
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
Generate Byte Array from Stream
提问by Anish
I am trying to generate byte array from a stream of ".rtf" file. The code is as follows:
我正在尝试从“.rtf”文件流生成字节数组。代码如下:
Public Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Try
Dim result As System.Nullable(Of Boolean) = textDialog.ShowDialog()
If result = True Then
Dim fileStream As Stream = textDialog.OpenFile()
GetStreamAsByteArray(fileStream)
End If
Catch ex As Exception
End Try
End Sub
Private Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) 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 above code generates stream length for the file opened however the byte array returned only have 0's in the array. How can i generate correct byte array?
上面的代码为打开的文件生成流长度,但是返回的字节数组在数组中只有 0。如何生成正确的字节数组?
回答by OneFineDay
You function does not returns the byte array to any object. This example works for me:
您的函数不会将字节数组返回给任何对象。这个例子对我有用:
Dim bytes = GetStreamAsByteArray(textDialog.File.OpenRead)
MessageBox.Show(bytes.Length.ToString)

