C# 从 url 下载和自定义进度条

C# Download from url and Custom progress bar

所以我做了一个可以从url下载字符串的软件。这是我的代码:

private void button1_Click(object sender, EventArgs e)
        {

    if (radioButton1.Checked)
                {

                    var accounts = new WebClient().DownloadString("https://pastebin.pl/view/raw/sample").Split('\n');
                    textBox1.Text = accounts[new Random().Next(0, accounts.Length)];
                }

如何制作由文本制作的自定义进度条,以便只显示用于下载进度的文本?示例:

当下载到10%的时候我想放文字进度条(状态:请求数据库)

当进度条到50%的时候我想放文字进度条(状态:获取信息)

100% 时(状态:已完成)

My Full Code

My Ui

你应该使用异步方法下载

   private void button1_Click(object sender, EventArgs e)
    {
        if (radioButton1.Checked)
        {
            Download(new Uri("https://pastebin.pl/view/raw/sample"));
        }
        else if (radioButton2.Checked)
        {
            Download(new Uri("https://pastebin.pl/view/raw/sample2"));
        }
        else if (radioButton3.Checked)
        {
            Download(new Uri("https://pastebin.pl/view/raw/sample4"));
        }
        else
        {
            MessageBox.Show(this, "select radio btn");
        }
    }

    private void  Download(Uri uri)
    {
        Thread thread = new Thread(() =>
        {
            WebClient client = new WebClient();
            client.DownloadProgressChanged += Client_DownloadProgressChanged1;
            client.DownloadStringCompleted += Client_DownloadStringCompleted;
            client.DownloadStringAsync(uri);
        });
        thread.Start();
    }

    private void Client_DownloadProgressChanged1(object sender, DownloadProgressChangedEventArgs e)
    {
        this.BeginInvoke((MethodInvoker)delegate {
            double bytesIn = double.Parse(e.BytesReceived.ToString());
            double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
            double percentage = bytesIn / totalBytes * 100;
            if(percentage >=10 && percentage <50)
            { 
              textBox1.Text ="message for 10%";   
            }
            else if if(percentage >=50 && percentage <100)
            {
                    textBox1.Text ="message for 50%";
            }
            else
            {
              textBox1.Text ="completed";
            }
            // you can use to show to calculated % of download
        });
    }



    private  void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {


        BeginInvoke((MethodInvoker)delegate
        {
            var accounts = e.Result.Split('\n');
            textBox1.Text = accounts[new Random().Next(0,accounts.Length)];
        });
    }

WebClient 已被弃用,取而代之的是 HttpClient,但这里是。

您应该使用 Progress<T> 报告进度。

您可以定义扩展方法,例如:

public static class WebClientExtensions
{
    public static async Task<string> DownloadStringTaskAsync(
        this WebClient webClient,
        string address,
        IProgress<int> progress)
    {
        try
        {
            webClient.DownloadProgressChanged += downloadProgressChanged;
            return await webClient.DownloadStringTaskAsync(address);
        }
        finally
        {
            webClient.DownloadProgressChanged -= downloadProgressChanged;
        }

        void downloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            progress.Report(e.ProgressPercentage);
        }
    }
}

并像这样使用它:

private async void button1_Click(object sender, EventArgs e)
{
    if (radioButton1.Checked)
    {
        var text = await new WebClient()
            .DownloadStringTaskAsync(
                "https://pastebin.pl/view/raw/sample",
                new Progress<int>(p => /* report progress */));
        var accounts = text.Split('\n');
        textBox1.Text = accounts[new Random().Next(0, accounts.Length)];
    }
}