Reading from a stream without knowing how much to expect [C #]

How can I read from a stream when I don't know in advance how much data will come in? Right now, I just selected the number on the high side (like in the code below), but there is no guarantee that I won't get more.

So I am reading a byte at a time in a loop, resizing the array each time? Sounds too much to resize: - /

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

      

+1


a source to share


6 answers


Putting it all together, assuming you don't end up with a HUGE (more than can fit in memory) amount of data:

TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(ip, port);
Stream stm = tcpclnt.GetStream();
stm.Write(cmdBuffer, 0, cmdBuffer.Length);
MemoryStream ms = new MemoryStream();
byte[] buffer = new Byte[2048];
int length;
while ((length = stm.Read(buffer, 0, buffer.Length)) > 0)
    ms.Write(buffer, 0, length);
tcpclnt.Close();
byte[] response = ms.ToArray();

      



As mentioned, MemoryStream

will handle the dynamic byte array allocation for you. And Stream.Read(byte[], int, int)

will return the length of the bytes found in this "read" or 0

if it reaches the end.

+3


a source


MemoryStream is your friend

http://msdn.microsoft.com/en-us/library/system.io.memorystream

      

Construct no default size and it will autoresist. Then just a loop where you suggest reading a reasonable amount of data each time. I usually choose MTU as the default buffer size.



To get the underlying byte [] array that makes the call

memoryStreamInstance.GetBuffer() 

      

+6


a source


Have you tried the StreamReader class? I'm not sure if it applies to this case, but I have used StreamReader to read HttpWebResponse response streams in the past. Very easy to use.

StreamReader reader = new StreamReader(stm);
String result = reader.ReadToEnd();

      

+3


a source


int count;
while ( (count = stm.Read(buffer, 0, buffer.Length)) > 0 ) {
   // process buffer[0..count-1]
   // sample:
   // memoryStream.Write(buffer, 0, count);
}

      

+1


a source


code:

byte[] buffer = new byte[1024];
int amt = 0;
while((amt = stm.Read(buffer, 0, 1024) != 0)
{
   // do something
}

      

slightly depends on what you get, if just plain text that you can store in a string device, if large amounts of binary data then store it with say memystream

0


a source


I guess it depends what you are going to do with the data?

If you don't need everything at once, can you just do the read operation inside the loop?

0


a source







All Articles