winforms 网络客户端下载进度已更改事件不起作用

qrjkbowd  于 2023-01-31  发布在  其他
关注(0)|答案(1)|浏览(147)

我使用以下代码从链接下载文件:

WebClient webClient = new WebClient();
webClient.Headers.Add("Accept: text/html, application/xhtml+xml, */*");
webClient.Headers.Add("User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
webClient.DownloadFileAsync(new Uri(downloadURL), "C:\\Users\\" + Environment.UserName + "\\Documents\\AudioStreamerUpdate_" + rnd1.ToString() + ".zip");

//track the downloading progress                      
webClient.DownloadProgressChanged += (sender, e) =>
{
    progressBar1.Value = e.ProgressPercentage;
    label1updateinf.Text = e.ProgressPercentage + "%";
    Console.WriteLine(e.ProgressPercentage + "%");
};

由于文件大小约为200 Mb,我希望跟踪下载进度。
我也试过这个代码:

webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressUpdate);

private void webClient_DownloadProgressUpdate(object sender, DownloadProgressChangedEventArgs e)
{

}

但它给了我一个错误
"DownloadProgressCallback"没有与委托"DownloadProgressChangedEventHandler"匹配的重载

t5zmwmid

t5zmwmid1#

如果在调用download方法 * 之前 * 附加事件处理程序,则代码应该可以工作:

public partial class MainForm : Form
{
    public MainForm() =>InitializeComponent();
    protected override async void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        SetWindowTheme(progressBar1.Handle, string.Empty, string.Empty);
        progressBar1.ForeColor = Color.Aqua;
        progressBar1.BackColor = Color.Gray;
        var path =
            Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                Application.ProductName,
                "DB.Browser.for.SQLite-3.12.2-win32.msi"
            );
        Directory.CreateDirectory(Path.GetDirectoryName(path));

        using (WebClient webClient = new WebClient())
        {
            // Attach event BEFORE downloading to receive progress
            webClient.DownloadProgressChanged += (sender, e) =>
            {
                progressBar1.Value = e.ProgressPercentage;
                label1updateinf.Text = e.ProgressPercentage + "%";
                Console.WriteLine(e.ProgressPercentage + "%");
            };
            try
            {
                webClient.DownloadFileAsync(new Uri("https://download.sqlitebrowser.org/DB.Browser.for.SQLite-3.12.2-win32.msi"), path);
            }
            catch (Exception ex)
            {
                Debug.Assert(false, ex.Message);
            }
        }
    }
    [DllImport("uxtheme", ExactSpelling = true, CharSet = CharSet.Unicode)]
    public extern static Int32 SetWindowTheme(IntPtr hWnd,
                    String textSubAppName, String textSubIdList);

}

相关问题