Nico Schreiner
Nico Schreiner

Reputation: 437

Should I use Stream.CopyToAsync() to copy data from a network stream?

I am getting data from the NetworkStream of a TcpClient and I want to write the data into a fixed-length MemoryStream, because I know the size of the data.

I use Stream.CopyToAsync to write the data into the MemoryStream:

var result = new MemoryStream(size);
await ns.CopyToAsync(result);
result.Position = 0;

return result;

Looking at the source code of Stream.CopyToAsync, the method terminates when there is no data in the source stream. In my case, when the network connection is slow or interrupted, my method would return an incomplete MemoryStream.

Can I ignore this possibility or should I read the stream by my own since I know how much data will be sent?

Upvotes: 2

Views: 9037

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

Since NetworkStream.Read will block1 until there is data and only return 0 if the connection is closed, I don't think this will meet your needs any better than CopyToAsync.

Since you already know how much data you're hoping to receive, I recommend just checking that the MemoryStream has the desired length:

var result = new MemoryStream(size);
await ns.CopyToAsync(result);

if (result.Length != size) {
     // it didn't load everything
}

result.Position = 0;

return result;

1 https://stackoverflow.com/a/6958290/3181933

Upvotes: 1

Related Questions