首页 > 解决方案 > C# - 下载时进度条保持在 0% (webclient)

问题描述

我一直在处理这个 xaml 文件。我想下载一个目标文件。据我所知,我可以下载文件,但是我的进度条不能正常工作(它保持在 0%)

由于我是这种语言的新手,所以我不知道所有参考文献等。所以也许我遗漏了一些东西。

这是完整的代码:(我有未使用的导入,但我稍后会删除它)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Forms;
using System.Windows.Shapes;
using System.Net.Mime;

namespace DownloadingFileWindow
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        WebClient client = new WebClient();
        string url = "https://download.filezilla-project.org/client/FileZilla_3.32.0_win64-setup_bundled.exe";

        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

            //client.OpenRead(url);
            //string header_contentDisposition = client.ResponseHeaders["content-disposition"];
            //string filename = new ContentDisposition(header_contentDisposition).FileName;

            if (!string.IsNullOrEmpty(url))
            {
                Thread thread = new Thread(() =>
                    {
                        Uri uri = new Uri(url);
                        string fileName = System.IO.Path.GetFileName(uri.AbsolutePath);
                        client.DownloadFileAsync(uri, System.Windows.Forms.Application.StartupPath + "/" + fileName);
                    });
                    thread.Start();
            }
        }

        private void MainWindow_Load(object sender, EventArgs e)
        {
            client.DownloadProgressChanged += Client_DownloadProgressChanged;
            client.DownloadFileCompleted += Client_DownloadFileCompleted;
        }

        private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            System.Windows.Forms.MessageBox.Show("Download OK!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
                progressBar.Minimum = 0;
                double receive = double.Parse(e.BytesReceived.ToString());
                double total = double.Parse(e.TotalBytesToReceive.ToString());
                double percentage = receive / total * 100;
                lblStatus.Text = $"{string.Format("{0:0.##}", percentage)}%";
                progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());
        }
    }
}

标签: c#wpf

解决方案


我认为存在多线程问题。由于您正在使用另一个线程进行下载,这就是为什么在 Client_DownloadProgressChanged 事件处理程序中,调度程序无法访问诸如 progressBar 和 lblStatus 之类的控件。

首先你应该写

progressBar.Minimum = 0;

MainWindow_Load 事件处理程序中的这一行,因为不需要在 progresschanged 事件处理程序中设置它。你应该更换

lblStatus.Text = $"{string.Format("{0:0.##}", percentage)}%";
progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());

if (!Dispatcher.CheckAccess())
{
    Dispatcher.Invoke(() =>
    {
        lblStatus.Content = $"{string.Format("{0:0.##}", percentage)}%";
        progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());
    });
}
else
{
    lblStatus.Content = $"{string.Format("{0:0.##}", percentage)}%";
    progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());
}

您可以在此处查看有关调度程序的文档。


推荐阅读