指定的参数超出了有效值的范围 - C#

时间:2013-11-28 17:41:27

标签: c#

我一直收到这个错误:

  

指定的参数超出有效值范围。

当我在C#中运行此代码时:

        string sourceURL = "http://192.168.1.253/nphMotionJpeg?Resolution=320x240&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;

这一行:

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

有人知道可能导致此错误的原因或解决方法吗?

提前致谢

1 个答案:

答案 0 :(得分:3)

  

有人知道可能导致此错误的原因吗?

我怀疑total(或更确切地说,total + 1000)超出了数组范围 - 如果您尝试读取超过200K的数据,则会出现此错误。

就我个人而言,我会以不同的方式处理它 - 我会创建一个MemoryStream来写入,一个更小的缓冲区来读取,总是在缓冲区的开头读取尽可能多的数据 - 然后将那么多字节复制到流中。然后只需将流回放(将Position设置为0),然后将其作为位图加载。

如果您使用的是.NET 4或更高版本,请使用Stream.CopyTo

Stream output = new MemoryStream();
using (Stream input = resp.GetResponseStream())
{
    input.CopyTo(output);
}
output.Position = 0;
Bitmap bmp = (Bitmap) Bitmap.FromStream(output);