如何获取richtextbox或文本框中所有链接的大小

时间:2014-01-30 19:37:31

标签: c#

我试图在richtextbox中获取我的直接链接的大小。在richtextbox中存在20或30个链接。我的代码适用于一个链接。我如何获得richtextbox中存在的所有链接的大小?这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(richTextBox1.Text);
    hwr.Method = "HEAD";
    HttpWebResponse res = (HttpWebResponse)hwr.GetResponse();
    long len = res.ContentLength;
    long a = len / 1024;
    long b = a / 1024;
    MessageBox.Show(b.ToString() + " MB");
}

1 个答案:

答案 0 :(得分:0)

我的建议取决于您的richTextBox.Text的样子,但如果它有一个已定义的分隔符 - 下面的代码应该有用 - 它会将文本拆分成行,然后在每一行执行请求:

private void button1_Click(object sender, EventArgs e)
{
    string[] movies = richTextBox1.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
    foreach (string item in movies)
    {
      item.Trim();
      HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(item);
      hwr.Method = "HEAD";
      HttpWebResponse res = (HttpWebResponse)hwr.GetResponse();
      long len = res.ContentLength;
      long a =len/1024;
      long b = a / 1024;
      MessageBox.Show(b.ToString()+" MB");
    }
}

编辑 - 我认为如果代码是异步的,代码会更好用,它看起来像这样:

    List<long> Length = new List<long>();
    List<string> Movies = new List<string>();

    private async void button1_Click(object sender, EventArgs e)
    {
        await getLength(Regex.Split(richTextBox1.Text, "\r\n|\r|\n"));
        string text = "";
        for (int i = 0; i < Movies.Count; i++)
            text += Movies[i] + " Length: " + Length[i].ToString() + "\n";
        MessageBox.Show(text);
    }

    private async Task getLength(string[] movies)
    {
        Task[] tasks = new Task[movies.Length];
        for (int i = 0; i < movies.Length; i++)
        {
            Movies.Add(movies[i].Trim());
            Length.Add(0);
            tasks[i] = getOnesLength(i);
        }
        await Task.WhenAll(tasks);
    }

    private async Task getOnesLength(int index)
    {
        HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(Movies[index]);
        hwr.Method = "HEAD";
        HttpWebResponse res = (HttpWebResponse) await hwr.GetResponseAsync();
        long len = res.ContentLength;
        long a = len / 1024;
        long b = a / 1024;
        Length[index] = b;
    }

在这种情况下,不应阻止您的UI,并且在获取所有链接的信息时,您应该看到MessageBox。当然这段代码缺少异常处理等等,但它可能是一个好的开始。