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:
(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?)