views:

192

answers:

2

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 shit")
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)
+1  A: 

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

Jon Skeet
I'm trying to read tcp data, what I get is a byte array (obviously), but I'm only interested in bytes 3 through 26, and it's the best way I could think of to get those bytes into a new byte array.
fMinkel
@fMinkel: Do you really have to get them into a new array, can't you just not use the first three bytes? Have you considered using Array.Copy to copy the data to the new array?
Guffa
Guffa, I had tried using Copy and CopyTo but I couldn't figure out how to use the middle of the source array, (3-26 out of an array that may be several thousand elements long)
fMinkel
@fMinkel: Array.Copy(source, 3, destination, 0, 24);
Guffa
+2  A: 

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()
Guffa