Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

c# - Handling two WebException's properly

I am trying to handle two different WebException's properly.

Basically they are handled after calling WebClient.DownloadFile(string address, string fileName)

AFAIK, so far there are two I have to handle, both WebException's:

  • The remote name could not be resolved (i.e. No network connectivity to access server to download file)
  • (404) File not nound (i.e. the file doesn't exist on the server)

There may be more but this is what I've found most important so far.

So how should I handle this properly, as they are both WebException's but I want to handle each case above differently.

This is what I have so far:

try
{
    using (var client = new WebClient())
    {
        client.DownloadFile("...");
    }
}
catch(InvalidOperationException ioEx)
{
    if (ioEx is WebException)
    {
        if (ioEx.Message.Contains("404")
        {
            //handle 404
        }
        if (ioEx.Message.Contains("remote name could not")
        {
            //handle file doesn't exist
        }
    }
}

As you can see I am checking the message to see what type of WebException it is. I would assume there is a better or a more precise way to do this?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Based on this MSDN article, you could do something along the following lines:

try
{
    // try to download file here
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
        {
            // handle the 404 here
        }
    }
    else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
    {
        // handle name resolution failure
    }
}

I'm not certain that WebExceptionStatus.NameResolutionFailure is the error you are seeing, but you can examine the exception that is thrown and determine what the WebExceptionStatus for that error is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...