2013-05-05 68 views
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塊不火。

回答

6

您需要處理DownloadFileCompleted事件,並檢查AsyncCompletedEventArgsError財產。

裏有鏈接很好的例子。

+1

,每次刪除一個空文件? – Paul 2013-05-05 19:12:19

+0

@Paul:是的,如果有錯誤。 'DownloadFileAsync'顯然會打開一個文件準備寫入。它在完成時關閉文件,錯誤或不。如果您不想要該文件,請將其刪除。 – 2013-05-05 19:17:43

3

你可以試試這個代碼:

WebClient wcl; 

void Test() 
{ 
    Uri sUri = new Uri("http://google.com/unknown/folder"); 
    wcl = new WebClient(); 
    wcl.OpenReadCompleted += onOpenReadCompleted; 
    wcl.OpenReadAsync(sUri); 
} 

void onOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) 
{ 
    if (e.Error != null) 
    { 
     HttpStatusCode httpStatusCode = GetHttpStatusCode(e.Error); 
     if (httpStatusCode == HttpStatusCode.NotFound) 
     { 
      // 404 found 
     } 
    } 
    else if (!e.Cancelled) 
    { 
     // Downloaded OK 
    } 
} 

HttpStatusCode GetHttpStatusCode(System.Exception err) 
{ 
    if (err is WebException) 
    { 
     WebException we = (WebException)err; 
     if (we.Response is HttpWebResponse) 
     { 
      HttpWebResponse response = (HttpWebResponse)we.Response; 
      return response.StatusCode; 
     } 
    } 
    return 0; 
}