【发布时间】:2015-02-17 05:57:21
【问题描述】:
这是我用来下载文件的方法。 我的程序正在使用计时器,它每 15 分钟尝试下载一次文件:
HttpWebRequest request;
int currentIndex = 0;
void fileDownloadRadar(string uri, string fileName)
{
if (splash != null)
{
if (!splash.IsDisposed)
splash.UpdateProgressBar(0);
}
try
{
request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.ContentType = "text/html";
request.CookieContainer = new CookieContainer();
request.AllowAutoRedirect = true;
request.Timeout = 10000;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
long contentLength = response.ContentLength;
if (response.ContentType == "")
{
Logger.Write("ContentType is Empty download was not fine !!!!!");
}
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
Logger.Write("ContentType is not empty meaning download is fine");
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
inputStream.ReadTimeout = 10000;
inputStream.WriteTimeout = 10000;
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
currentIndex += bytesRead;
double percentage = (double)currentIndex / contentLength;
if (splash != null)
{
if (!splash.IsDisposed)
splash.UpdateProgressBar((int)(percentage * 100));
}
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
if (splash != null)
{
if (!splash.IsDisposed)
{
splash.UpdateProgressBar(100);
}
}
}
}
else
{
timer1.Stop();
timer3.Start();
}
if (splash == null)
FinishWebRequest();
}
}
catch (Exception ex)
{
Logger.Write(ex.ToString());
}
}
该程序运行了几个小时,然后大约 30 分钟前它抛出了这个异常:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
WebException: 远程服务器返回错误:(404) Not Found
完整的异常消息:
System.Net.WebException occurred
HResult=-2146233079
Message=The remote server returned an error: (404) Not Found.
Source=System
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at mws.Form1.fileDownloadRadar(String uri, String fileName) in d:\C-Sharp\Download File\Downloading-File-Project-Version-012\Downloading File\Form1.cs:line 1015
InnerException:
第 1015 行是:
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
它没有跳转到catch部分,只是在这一行抛出异常。 我的问题我应该如何处理这种情况?
也许,我想在出现此异常的情况下调用一个方法,该方法将尝试下载文件 15 次,每次 30 秒尝试,如果 15 次后没有下载,则继续下一个 15 分钟.但我不确定这是否是一个好的解决方案,无论如何我应该如何处理异常?我添加了 try and catch,但没有成功。
【问题讨论】: