c#中网络异常的处理办法

加入try catch来判断,catch使用的WebException来处理

try

{

    var request = WebRequest.Create(uri);

    using (var response = request.GetResponse())

    {

        using (var responseStream = response.GetResponseStream())

        {

            // Process the stream

        }

    }

}

catch (WebException ex)

{

    if (ex.Status == WebExceptionStatus.ProtocolError &&

        ex.Response != null)

    {

        var resp = (HttpWebResponse) ex.Response;

        if (resp.StatusCode == HttpStatusCode.NotFound)

        {

            // Do something

        }

        else

        {

            // Do something else

        }

    }

    else

    {

        // Do something else

    }

}

 

你可能感兴趣的:(C#)