c# 下载文件并处理进度

我们先来个Form

复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            byte[] data = client.DownloadData("http://b.hiphotos.baidu.com/zhidao/pic/item/3c6d55fbb2fb4316641d646623a4462309f7d3af.jpg");//一个真正存放数据的地址,一般我们将连接存在数据库中,数据存放在数据服务器上
            //如果网站没有什么限制的话,这样就能得到网站的图片数据了
            string path =Application.StartupPath;
            FileStream fs = new FileStream(path+"\\x.jpg", FileMode.Create);   
            //将byte数组写入文件中
            fs.Write(data,0,data.Length);     
            fs.Close();
        }
    }
}
复制代码

 这里关键就是 System.Net.WebClient 这个类的用法,官方文档网址:https://docs.microsoft.com/zh-cn/dotnet/api/system.net.webclient?view=net-6.0

比如我们要处理下载进度:

复制代码
// Sample call : DownLoadFileInBackground4 ("http://www.contoso.com/logs/January.txt");
public static void DownLoadFileInBackground4(string address)
{
    WebClient client = new WebClient();
    Uri uri = new Uri(address);

    // Specify a DownloadFileCompleted handler here...

    // Specify a progress notification handler.
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback4);

    client.DownloadFileAsync(uri, "serverdata.txt");
}

private static void DownloadProgressCallback4(object sender, DownloadProgressChangedEventArgs e)
{
    // Displays the operation identifier, and the transfer progress.
    Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
        (string)e.UserState,
        e.BytesReceived,
        e.TotalBytesToReceive,
        e.ProgressPercentage);
}
复制代码

 

posted @   otkur  阅读(611)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示