2013-11-28 50 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!它工作完美 –

相關問題