0

I have this simple function which Tries to get a pages Html, returns null if an exception is thrown

 public static string TryGetPageHtml(string link, System.Net.WebProxy proxy = null)
        {
            System.Net.WebClient client = new System.Net.WebClient() { Encoding = Encoding.UTF8 };
            if (proxy != null)
            {
                client.Proxy = proxy;
            }

            using (client)
            {
                try
                {
                    return client.DownloadString(link);
                }
                catch (Exception ex)
                {
                    return null;
                }
            }

        }

i want to call this function 3 times if it returns null three times that means it faild, so i came up with the following

one way to do that is

        string HTML = null;
        int triesRemaining = 3;
        while (HTML == null && triesRemaining--!=0)
        {
            HTML = TryGetPageHtml(link,getrandomproxy());
        }
        if(HTML == null){//do the handlig}

and another i came up with is

HTML = TryGetPageHtml(link,getrandomproxy())??TryGetPageHtml(link,getrandomproxy())??TryGetPageHtml(link,getrandomproxy());
             if(HTML == null){//do the handlig}

is there a better way and are there built in things in .net that could make this more readable?

Cœur
  • 37,241
  • 25
  • 195
  • 267
FPGA
  • 3,525
  • 10
  • 44
  • 73

3 Answers3

3

Could do a for loop with a break when it found the html:

        string HTML = null;
        for (int i = 0; i < 3; i++)
        {
            HTML = TryGetPageHtml(link, getrandomproxy());
            if (HTML != null)
                break;
        }
PCG
  • 1,197
  • 9
  • 23
1

Or you could set this up as a recursive function that took the number of attempts as an argument.

public static string TryGetPageHtml(string link, int attempCount = 1,
 System.Net.WebProxy proxy = null, string foundHTML = null)
{
    if(attemptCount == 0 || foundHTML != null)
    {
        return foundHTML;
    }

    if (proxy != null)
    {
        client.Proxy = proxy;
    }

    using (System.Net.WebClient client = new System.Net.WebClient())
    {
        client.Encoding = Encoding.UTF8;

        try
        {
            foundHTML = client.DownloadString(link);
        }
        catch (Exception ex)
        {
            return null; //Remove this if we want to retry on exception
        }
        finally
        {
            return TryGetPageHtml(link, --attemptCount, proxy, foundHTML);
        }
    }
}
Carth
  • 2,303
  • 1
  • 17
  • 26
0

How about this? More readable probably.

var iCount = 0;
string HTML = null;

while (iCount++ < 3 && HTML == null)
{
    HTML = TryGetPageHtml(link, getrandomproxy());
}
Adarsh Shah
  • 6,755
  • 2
  • 25
  • 39