2013-11-28 47 views
0

我不断收到此错误:指定的参数是有效的值的范围之外 - C#

The specified argument is outside the range of valid values.

当我运行这段代码在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) 

有谁知道什么可能会导致此错误或如何解决它?

在此先感谢

回答

3

Does anybody know what could cause this error?

我怀疑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); 
+1

大约只是在做'Bitmap.FromStream(输入)什么'直接? –

+0

Thx!它工作完美 –

相关问题