3
此代碼:如何捕捉404引發WebException爲WebClient.DownloadFileAsync
try
{
_wcl.DownloadFile(url, currentFileName);
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)
Console.WriteLine("\r{0} not found. ", currentFileName);
}
下載文件,並通知404,如果出現錯誤。
我決定異步下載文件:
try
{
_wcl.DownloadFileAsync(new Uri(url), currentFileName);
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
if ((ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.NotFound)
Console.WriteLine("\r{0} not found. ", currentFileName);
}
現在,如果服務器返回404錯誤和Web客戶端產生一個空文件這個catch塊不火。
,每次刪除一個空文件? – Paul 2013-05-05 19:12:19
@Paul:是的,如果有錯誤。 'DownloadFileAsync'顯然會打開一個文件準備寫入。它在完成時關閉文件,錯誤或不。如果您不想要該文件,請將其刪除。 – 2013-05-05 19:17:43