开发者

Writing a byte array to memorystream yields only zeros being written?

开发者 https://www.devze.com 2022-12-16 09:27 出处:网络
I\'ve tried rewriting this code several times, it spits out the bytes correctly, but then when trying to read the array created from the memory stream, it\'s empty, what am I doing wrong?

I've tried rewriting this code several times, it spits out the bytes correctly, but then when trying to read the array created from the memory stream, it's empty, what am I doing wrong?

Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes("test this code")
Dim bytesString As String = ""
Dim i As Integer = 0
i = 0
Dim byteStream As New System.IO.MemoryStream
Do While i < bytes.Length
    If bytes(i).ToString <> 0 Then
        bytesString = bytesString & "|" & bytes(i).ToString
        byteStream.WriteByte(bytes(i))
        Debug.Print(bytes(i).ToString)
 开发者_运维问答   End If
    i = i + 1
Loop
i = 0
byteStream.Flush()
Dim newBytes(byteStream.Length - 1) As Byte
byteStream.Read(newBytes, 0, byteStream.Length)
byteStream.Close()
Dim stringData As String = System.Text.Encoding.ASCII.GetString(newBytes)
Debug.Print("Data: " & stringData)


You're not rewinding the stream before you read:

byteStream.Position = 0

(Just before the call to Read.)

Basically you're not actually reading any data, because the stream is positioned at the end when you call Read.

This is another reason why you should check the return value of Read... it'll be returning 0, which would have given you a hint.

(It's also not at all clear to me why you're converting each byte to a string, and then comparing it with an integer... what is this code really meant to be doing?)


I'll post this as an answer to explore some alternatives:

If you just want to copy the data from one array to another, you don't have to use a stream. Just do:

Dim newBytes(23) As Byte
Array.Copy(bytes, 3, newBytes, 0, 24)

(Note that bytes 3 through 26 is not 23 bytes, as one is easily fooled into thinking, but 24. Declaring newBytes(23) gives you an array with the highest index of 23 and thus the length 24.)

You can also just copy the bytes one at a time:

Dim newBytes(23) As Byte
For i As Integer = 0 To newBytes.Length - 1
   newBytes(i) = bytes(i + 3)
Next

Another option (that is not quite as efficent but short and easy to understand) is to use LINQ methods to get the bytes and turn into an array:

Dim newBytes As Byte() = bytes.Skip(3).Take(24).ToArray()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号