C# 在使用webclient下载一整个文件夹的时候, 显示下载进度条

在C# winform编程中,有一个进度条的控件叫 ProgressBar,可以通过代码设置它的属性,然后我们就可以实现下载的时候显示进度条。

对于文件夹的下载,由于文件夹里面可能存在文件和文件夹,而C#仅支持对文件的下载,所以需要通过递归搜索,遍历文件夹的方式进行下载。

public void Download(string savePath, string sourcePath)
{
    if (!File.Exists(savePath))
    {
        Directory.CreateDirectory(savePath);
    }
    string[] dirs = Directory.GetDirectories(sourcePath);
    string[] files = Directory.Files(sourcePath);

    if (files.Length > 0)
    {
        for (int i = 0; i < files.Length; i++)
        {
            WebClient client = new WebClient();
            // 绑定事件
            client.DownloadProgressChanged += client_DownloadProcessChanged;
            // 异步下载
            client,DOwnloadFileAsync(new Uri(sourcePath + "\\" + Path.GetFileName(files[i]), savePath + "\\" + Path.GetFileName(fles[i])));
            Application.DoEvents()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中,你可以使用WebClient类来下载文件并限制下载速度。你需要使用System.Threading命名空间中的Thread.Sleep方法来暂停下载,并将速度限制为所需的速度。 以下是一个简单的示例代码,它将下载速度限制为10KB/s: ``` using System.Net; using System.Threading; public void DownloadFile(string url, string fileName) { WebClient client = new WebClient(); client.DownloadProgressChanged += WebClient_DownloadProgressChanged; client.DownloadFileCompleted += WebClient_DownloadFileCompleted; using (var stream = client.OpenRead(url)) using (var output = File.Create(fileName)) { byte[] buffer = new byte[1024]; int bytesRead = 0; int downloadSpeed = 10 * 1024; // 10KB/s DateTime startTime = DateTime.Now; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, bytesRead); // 计算已下载的字节数和时间 long bytesDownloaded = output.Position; double secondsElapsed = (DateTime.Now - startTime).TotalSeconds; // 计算当前下载速度,并暂停下载 int currentSpeed = (int)(bytesDownloaded / secondsElapsed); if (currentSpeed > downloadSpeed) { int sleepTime = (int)(1000 * ((double)bytesRead / downloadSpeed - secondsElapsed)); if (sleepTime > 0) Thread.Sleep(sleepTime); } } } } private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { // 下载进度改变时的操作 } private void WebClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { // 下载完成时的操作 } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值