首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Webclient.DownloadString崩溃

Webclient.DownloadString崩溃
EN

Stack Overflow用户
提问于 2010-09-30 16:23:50
回答 1查看 1.2K关注 0票数 1

我有一个名为GetIP的函数,我在启动和用户按下按钮时调用它。由于某种原因,它在启动时不会崩溃,但在使用按钮调用函数时会崩溃。没有异常,什么都没有,它只是冻结了。

函数代码:

代码语言:javascript
复制
        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];
        }

现在我发现它在我的getWebPageTitle函数中崩溃了

函数代码:

代码语言:javascript
复制
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;
    }

它在web.DownloadString上崩溃

对于crash,我的意思是冻结,不显示任何exeptions等。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-09-30 16:53:44

好吧,我不能说我知道它为什么会冻结,但这里有一些建议可能会有所帮助:

完成后(例如,当您从该方法返回时),

  • 调用response.Close()
  • WebClient类实现了IDisposable,因此您应该尝试每次使用Regex类中的静态方法为单个匹配创建新的Regex对象。
  • 尝试将web.Proxy属性设置为null,以确保它不会尝试检测代理(默认情况下)。<代码>H211<代码>F212
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3828934

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档