Using arrays : Is this the best code to use for reading from a networkstream (vb.net)? on newest questions tagged arrays – Stack Overflow

I know it’s subjective but this was the result I came up with based on the answer to me previous question and it seems a bit “slapped together”, as I have changed it quite a bit:

  Private Function ReadFromBuffer(ByVal objReader As NetworkStream) As Byte()
    Dim intRead As Integer = 1024
    Dim allBytes(-1) As Byte

    While intRead = 1024
        Dim byteTempbuffer(1023) As Byte
        intRead = objReader.Read(byteTempbuffer, 0, 1024)
        ReDim Preserve byteTempbuffer(intRead - 1)
        Dim tempold(allBytes.Length - 1) As Byte
        tempold = allBytes
        allBytes = tempold.Concat(byteTempbuffer).ToArray
    End While

    Return allBytes
End Function

Basically is there a better way to write this (even just part of the code) or a more efficient way to do it?

Basically the code is there to read all the bytes from a networkstream 1024 bytes at a time. And each time it reads the bytes it puts into one array which is returned.

The thing i think might be better is only Redim byteTempbuffer if intRead is less than 1024 (the redim is to prevent empty bytes from being added to the end of the array when there are less the 1024 bytes left to read from the networkstream) (basically is it more efficent to Redim every time or to go through and if statement and redim only if needed)

See Answers


source: http://stackoverflow.com/questions/2031405/is-this-the-best-code-to-use-for-reading-from-a-networkstream-vb-net
Using arrays : using-arrays



online applications demo