Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stream.Read sometimes returns -1, what to do?

Status
Not open for further replies.

mirzapirza

Technical User
Oct 25, 2003
12
SE
It's not documented in the MSDN. The Read method is supposed to return the number of bytes read from the stream, or 0 if there's no more data.

Here's what I'm currently doing..

Code:
// reader is a Stream
using(reader = new WebClient().OpenRead(url))
{
	int read = 1;
	byte[] buff = new byte[4096];
	while(read != 0)
	{
		read = reader.Read(buff, 0, buff.Length);

		if(read > 0)
			writer.Write(buff, 0, read);
	}
}

Any ideas on how this -1 should be handled? I can't seem to find it documented anywhere.

 
I think you might have found a bug. The return value is definitely a count of bytes read, and you can't have a negative count of anything.

I would just test for it being less than 1.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
I don't think the Stream.Read() returns -1.
The Stream.ReadByte{} could return -1 when the end stream.
You should write:
while(read >= 0)
{
...
}
-obislavu-
 
obislavu, it does. Even when I use WebClient.DownloadFile I sometimes catch exceptions with an inner ArgumentException coming from the Stream.Read saying that the parameter 'count' can't be negative. :)

I was wondering how i should interpret this? Should I treat -1 like 0 and assume there's no more?

I guess I'll look around a bit and then send something to microsoft's newsgroups and see if they're fixing this.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top