我写了一段从网址下载文件的简单代码。此代码在Windows 7中运行良好,以良好的速度下载文件并维护显示下载进度的进度条。但是,当我从Windows XP SP2运行相同的代码时,它会产生.NET IOException ,对我来说没有意义,为什么它不起作用。它启动相同,正确完成第一次读取,然后在第二次尝试从流中读取时抛出以下异常:
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)
代码:
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 :(得分:1)
您下载的文件超过300兆字节,您尝试从流中一次读取。
您最好以块方式读取流,例如4MByte块。