How can I read from a stream when I don’t know in advance how much data will come in? Right now I just picked a number on a high side (as in code below), but there’s no guarantee I won’t get more than that.
So I read a byte at a time in a loop, resizing array each time? Sounds like too much resizing to be done :-/
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(ip, port);
Stream stm = tcpclnt.GetStream();
stm.Write(cmdBuffer, 0, cmdBuffer.Length);
byte[] response = new Byte[2048];
int read = stm.Read(response, 0, 2048);
tcpclnt.Close();
Putting it all together, assuming you’re not getting a HUGE (more than can fit into memory)amount of data:
As mentioned the
MemoryStreamwill handle the dynamic byte array allocation for you. AndStream.Read(byte[], int, int)will return the length of the bytes found in this ‘read’ or0if it’s reached the end.