-1

When i use other questions' answers i get a WebException and it crashes, here is the following code i tried:

WebClient Client = new WebClient ();
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");

And I get a WebException when I click the button of the download, so anyone got a fix for this problem? I'm trying to download a file from a url without getting a WebException.

Filburt
  • 17,626
  • 12
  • 64
  • 115

1 Answers1

0

You can handle errors like this, so that you can easily debug through the cause of error.

Please go through Status values here, there is more to handle

try
        {           

            using (var client = new WebClient())
            {
                client.DownloadFile({url},{filename to save});

            }               
        }
        catch (WebException ex)
        {
            if(ex.Status==WebExceptionStatus.Timeout) //Timeout 
            {

            }
            if (ex.Status == WebExceptionStatus.ConnectFailure) //Connection error 
            {

            }
            if (ex.Status == WebExceptionStatus.NameResolutionFailure) //URL not valid
            {

            }
            if (ex.Response!= null)
            {
                if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
                {
                    // error 404, do what you need to do

                }                   
            }               

        }