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); }
标签:下载,string,c#,System,client,进度,new,using,WebClient 来源: https://www.cnblogs.com/otkur/p/16607298.html