views:

23

answers:

1

I have a function called GetIP which I call on startup and when the user presses a button. for some reason it does not crash on startup, but it does when calling the function with a button. No exeptions nothing it just freezes.

code for function :

        private void GetIP()
        {
        string pageTitle = functions.GetWebPageTitle("http://xyro18.woelmuis.nl/index.php");
        string[] ip = new string[2];
        ip = pageTitle.Split('|');
        currentIpLabel.Text = ip[0];
        webIpLabel.Text = ip[1];
        }

Now I found out that it crashes in my getWebPageTitle function

code for function :

public static string GetWebPageTitle(string url)
    {
        // Create a request to the url
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.Method = "HEAD";
        // If the request wasn't an HTTP request (like a file), ignore it
        if (request == null) return null;

        // Use the user's credentials
        request.UseDefaultCredentials = true;

        // Obtain a response from the server, if there was an error, return nothing
        HttpWebResponse response = null;
        try { response = request.GetResponse() as HttpWebResponse; }
        catch (WebException) { return null; }

        // Regular expression for an HTML title
        string regex = @"(?<=<title.*>)([\s\S]*)(?=</title>)";

        // If the correct HTML header exists for HTML text, continue
        if (new List<string>(response.Headers.AllKeys).Contains("Content-Type"))
            if (response.Headers["Content-Type"].StartsWith("text/html"))
            {
                // Download the page
                WebClient web = new WebClient();
                web.UseDefaultCredentials = true;
                string page = web.DownloadString(url);

                // Extract the title
                Regex ex = new Regex(regex, RegexOptions.IgnoreCase);
                return ex.Match(page).Value.Trim();
            }

        // Not a valid HTML page
        return null;
    }

It crashes on the web.DownloadString

with crash I mean freeze and does not display any exeptions etc.

A: 

Well, I can't say I know why it freezes, but here are some suggestions that may help:

  • Call response.Close() when you're done with it (e.g. when you return from the method).
  • The WebClient class implements IDisposable, so you should try the using construct.
  • Instead of creating a new Regex object every time for a single match, use the static methods in the Regex class.
  • Try setting the web.Proxy property to null, to make sure that it doesn't try to detect a proxy (as it would by default).
ShdNx
Thanks it worked, implemented all of the options, it seemed to be me not closing the response signal.
Quincy