2012-05-01 218 views
0

我寫了一段從網址下載文件的簡單代碼。此代碼在Windows 7中完美工作,以很快的速度下載文件並保持顯示下載進度的進度條。但是,當我從Windows XP SP2運行同一段代碼時,它會產生一個.NET IOException ,這對我來說毫無意義,爲什麼它不起作用。它開始一樣,正確地完成了第一次讀,然後拋出以下異常在第二次嘗試從流中讀取:下載代碼適用於Windows 7,但不適用於XP SP2?

System.IO.IOException: Unable to read data from the transport connection: An operation on a 
socket could not be performed because the system lacked sufficient buffer space or because a 
queue was full. ---> 

System.Net.Sockets.SocketException: An operation on a socket could not be 
performed because the system lacked sufficient buffer space or because a queue was full 
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) 

at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) 
--- End of inner exception stack trace --- 
at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size) 
at ServicePackChk.SrvPackChk.DownLoadServicePack(Boolean bWindowsXP) 
at ServicePackChk.SrvPackChk.CheckServicePackStatus() 
at ServicePackChk.Form1.Form1_Load(Object sender, EventArgs e) 
at System.Windows.Forms.Form.OnLoad(EventArgs e) 

CODE:

 Uri uri; 

     if (bWindowsXP) 
      uri = new Uri("http://download.microsoft.com/download/d/3/0/d30e32d8-418a-469d-b600-f32ce3edf42d/WindowsXP-KB936929-SP3-x86-ENU.exe"); 
     else 
      uri = null; 

     WebRequest req = WebRequest.Create(uri); 
     WebResponse resp = req.GetResponse(); 

     ProgBarForm pform = new ProgBarForm(); 

     updateEvent += new SrvPackChk.UpdateDownloaded(pform.UpdateProgBar); 

     Stream stream = resp.GetResponseStream(); 
     ArrayList alBytes = new ArrayList(); 
     int nLen = (int)resp.ContentLength; 


     pform.DownLoadSize = nLen; 

     pform.Show(); 

     byte[] byExe = new byte[nLen]; 

     bool bMoreToDownload = true; 

     FileStream fs = new FileStream(System.IO.Path.GetTempPath() + "XPSP3.exe", FileMode.Create); 

     MessageBox.Show("Saving File to " + System.IO.Path.GetTempPath() + "XPSP3.exe"); 

     while (bMoreToDownload) 
     { 
      Application.DoEvents(); 

      int nRead = 0; 

      nRead = stream.Read(byExe, 0, nLen); 

      nDownloaded += nRead; 

      updateEvent(nDownloaded); 

      if (nDownloaded == nLen) 
      { 
       bMoreToDownload = false; 
      } 

      fs.Write(byExe, 0, nRead); 
      fs.Flush(); 

      Application.DoEvents(); 
     } 

     stream.Close(); 

     fs.Close(); 
+0

而不是分配'resp.ContentLength'字節數組,嘗試讀取塊。 –

回答

1

你下載的文件有300兆字節您嘗試從流中一次讀取。

你最好應該讀取流的塊,例如4MByte塊。

+0

無論如何,它在塊中讀取,我要求整個長度,但我得到的數據塊,變量nRead = 78288在XP上第一次成功讀取,隨後的讀取拋出異常,所以我不能確定這是一個問題嗎? –

+0

後續讀取的大小是多少?當你讀取流時,你可以傳遞比nLen更小的值,只是爲了看看會發生什麼。 – thumbmunkeys

+0

第二次讀取會拋出異常,如同所有進一步讀取一樣。我試過nLen - nDownloaded,然而,程序只是等待讀取返回,它從來沒有。 –

相關問題