客户端停止下载网站源代码c#

问题描述

我正在尝试下载网站的源代码,一旦按下按钮开始检索,程序就会无限卡住

我的代码


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender,EventArgs e)
        {
            using (WebClient client = new WebClient())
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                string html = client.DownloadString("https://www.finanzen.net/termine/unternehmen/");
                MessageBox.Show(html);
            }
        }
    }
}

如何解决此问题?任何帮助表示赞赏:)

解决方法

您对穷人MessageBox.Show的要求很高。 html的长度为423,467个字符。尝试以下方法:

MessageBox.Show(html.Substring(0,Math.Min(html.Length,1000)));
,

我更喜欢使用方法的异步实现。请参见下面的示例:

private async void button1_Click(object sender,EventArgs e)
        {
            using (WebClient client = new WebClient())
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                string html = await client.DownloadStringAsync("https://www.finanzen.net/termine/unternehmen/");
                MessageBox.Show(html);
            }
        }

编辑: 建议您不要在GUI中显示结果,而不是在MessageBox中显示结果。结果将存储在列表中,然后显示在GUI上。