我有以下用于下载文件的方法。它工作正常,除非在下载过程中互联网连接断开。在这种情况下,它会卡在接收流的读取(即在 len = receiveStream.Read(buffer, 0, buffer.Length) 中。它不会继续,或者抛出异常,它似乎永远卡在那里。我将超时设置为 10 秒,并将它们赶得更高。我做错了什么,还是错过了什么?
我也尝试过使用异步方法(BeginGetResponse、BeginRead 等),但它们也卡住了。
我已经在 Windows mobile 6 专业模拟器和 Windows 移动设备上对此进行了测试。
private void DownloadFile(string url, string filename)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 10000;
request.ReadWriteTimeout = 10000;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream receiveStream = response.GetResponseStream())
{
long size = response.ContentLength;
using (Stream file = File.OpenWrite(filename))
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = receiveStream.Read(buffer, 0, buffer.Length)) > 0)
{
file.Write(buffer, 0, len);
total += len;
UpdateDownloadState(total, size);
}
}
}
}
}
谢谢