John Smith
John Smith

Reputation: 11

How to know that the stream has ended C#

I'm trying to recieve a tcp packet in C# but I don't know when can I stop reading from the stream. Here's what I've tried:

for(int i = 0; i < stm.Length; i += chunkSize)
{
    bb = new byte[chunkSize];
    k = stm.Read(bb, 0, bb.Length);
    ns.Write(bb, 0, k);
}

But it threw me an error about that the stream is not seekable. So I've tried this:

int k = chunkSize;

while (k == chunkSize)
{
    bb = new byte[chunkSize];
    k = stm.Read(bb, 0, bb.Length);
    ns.Write(bb, 0, k);
}

Is there anything to do? Thanks :)

Upvotes: 1

Views: 987

Answers (2)

Anirudha
Anirudha

Reputation: 32787

a binary reader is what you would require since it knows exactly how many bytes to read!

It prefixes the length of the bytes and so it knows how much to read!

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062520

Here we go:

int read;
while((read = stm.Read(bb, 0, bb.Length)) > 0) {
    // process "read"-many bytes from bb
    ns.Write(bb, 0, read);
}

"read" will be non-positive at the end of the stream, and only at the end of the stream.

Or more simply (in 4.0):

stm.CopyTo(ns);

Upvotes: 4

Related Questions