Pregunta

I'm trying to remove a node from an xml file, everything works, but sometimes it happens that the xml web page does not load. this is my code:

private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
            if (e.Error == null)
            {
                XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);

                    var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
                    TextBlock1.Text = lyric.Value;


            }

        }
    }

    private void btnLoad_Click(object sender, RoutedEventArgs e)
    {



        WebClient wc = new WebClient();
        wc.DownloadStringCompleted += HttpsCompleted;
        wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad));


    }

I' ve read to use the WebException to handle this "mistake" but I am not able to use it. can someone give me some help?

¿Fue útil?

Solución

Have you tried this way?

    private void btnLoad_Click(object sender, RoutedEventArgs e)
    {
        try
        {

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += HttpsCompleted;
            wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad"));
        }
        catch (WebException ex)
        {
            // Check the exception here
        }
    }

And check for error in the handler too:

private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    if (e.Error == null)
    {
        XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
        if (e.Error == null)
        {
            XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);

                var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
                TextBlock1.Text = lyric.Value;
        }       
    }
    else
    {
        // Check for error here
    }
}

I realized it sometimes return Error, and I think the problem is in the server, because if I access it from the web browser, I sometimes get the result, but many times I get an error.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top