• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1046
  • Last Modified:

Read a NetworkStream to byte[] array

Hi Experts,

Here is my method:
private byte[] ReadNetworkStream(NetworkStream networkStream, int buffer)
        {
            ArrayList arrayList = new ArrayList();
            if (networkStream.CanRead)
            {
                byte[] readBuffer = new byte[buffer];
                int bytesRead = 0;

                // Incoming message may be larger than the buffer size.
                do
                {
                    Console.WriteLine("reading");
                    bytesRead = networkStream.Read(readBuffer, 0, buffer);
                    Console.WriteLine("readed");
                    if (bytesRead == buffer)
                        arrayList.Add(readBuffer);
                    else if (bytesRead > 0 && bytesRead < buffer)
                    {
                        byte[] endRead = new byte[bytesRead];
                        Array.Copy(readBuffer, endRead, bytesRead);
                        arrayList.Add(endRead);
                        break;
                    }
                    else
                        break;
                }
                while (networkStream.DataAvailable);
            }
            return (byte[])arrayList.ToArray(typeof(byte));
        }

But it doesn't work. (I don't want to use Encoding, because I only want binary datas)

Thanks in advance for your help.
0
noulouk
Asked:
noulouk
2 Solutions
 
pallospCommented:
The DataAvailable indicates if the network buffer is not empty. Your method may return prematurely without reading everything.
The data is only read completely, when the Read method returns 0.
0
 
Expert1701Commented:
Hello noulouk,

  I believe if you use ArrayList.AddRange instead of ArrayList.Add the method will work as you intended.
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now