Q:

The specified argument is outside the range of valid values - C#

I keep getting this error: 

The specified argument is outside the range of valid values.

When I run this code in C#:
        string sourceURL = "http://192.168.1.253/nphMotionJpeg?Resolution=320x240&amp;Quality=Standard";
        byte[] buffer = new byte[200000];
        int read, total = 0;
        // create HTTP request
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sourceURL);
        req.Credentials = new NetworkCredential("username", "password");
        // get response
        WebResponse resp = req.GetResponse();
        // get response stream
        // Make sure the stream gets closed once we're done with it
        using (Stream stream = resp.GetResponseStream())
        {
            // A larger buffer size would be benefitial, but it's not going
            // to make a significant difference.
            while ((read = stream.Read(buffer, total, 1000)) != 0)
            {
                total += read;
            }
        }
        // get bitmap
        Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, 0, total));
        pictureBox1.Image = bmp;

This line:
while ((read = stream.Read(buffer, total, 1000)) != 0)

Does anybody know what could cause this error or how to fix it?
Thanks in advance

A:

Does anybody know what could cause this error?

I suspect total (or rather, total + 1000) has gone outside the range of the array - you'll get this error if you try to read more than 200K of data.
Personally I'd approach it differently - I'd create a MemoryStream to write to, and a much smaller buffer to read into, always reading as much data as you can, at the start of the buffer - and then copying that many bytes into the stream. Then just rewind the stream (set Position to 0) before loading it as a bitmap.
Or just use Stream.CopyTo if you're using .NET 4 or higher:
Stream output = new MemoryStream();
using (Stream input = resp.GetResponseStream())
{
    input.CopyTo(output);
}
output.Position = 0;
Bitmap bmp = (Bitmap) Bitmap.FromStream(output);

