C # The problem of operation timeout when downloading file with WebClient

Source: Internet
Author: User

This is the original code:

System.Net.WebClient WC = new System.Net.WebClient ();

Wc. OpenRead ("Http://patrickkroft.com/mp3/Pearl.mp3");

Int64 bytes_total= convert.toint64 (WC. responseheaders["Content-length"])

MessageBox.Show (bytes_total. ToString () + "Bytes");



The above code is really not responsible, the pit father writes. Improved into the following:

System.Net.WebClient WC = new System.Net.WebClient ();

Stream stream = WC. OpenRead (Folderentity.uri);
Int64 bytes_total = Convert.toint64 (WC. responseheaders["Content-length"]);
Stream. Close (); and freeing up memory
Wc. Dispose ();//release in time to avoid the strange "Operation timeout" problem when downloading for the second time

Download the file asynchronously with WebClient, but if an exception occurs during the download (for example, the URL does not exist, the network is interrupted, etc.), the 0-byte file is downloaded, and the downloadfilecompleted event is also activated after the download of 0 bytes is complete.

I want to catch an exception during an asynchronous download, activate an event to jump to another branch to execute the program if the URL does not exist (for example, Pop-up dialog prompts for download failure)

How should I catch the exception of DownloadFileAsync?

DownloadFileAsync does throw a WebException exception when the download fails, but this exception is not caught with Try...catch. NET is automatically passed to the AsyncCompletedEventArgs parameter E in the Downloadfilecompleted event, and the exception is obtained by E.error.

C # The problem of operation timeout when downloading file with WebClient

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.