WebClient的使用
Posted lunawzh
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebClient的使用相关的知识,希望对你有一定的参考价值。
1、下载网页源码:
private void button1_Click(object sender, EventArgs e) { string url = textBox1.Text; string toUrl = Application.StartupPath + "\\" + Path.GetFileName(url); WebClient wc = new WebClient(); wc.DownloadDataAsync(new Uri(url)); wc.DownloadDataCompleted += wc_DownloadDataCompleted; } void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { if (e.Error == null && e.Cancelled == false) textBox2.Text = Encoding.UTF8.GetString(e.Result); else MessageBox.Show(e.Error.Message); }
2、直接下载文件,比较简单,但下载比较伤硬盘:
private void button1_Click(object sender, EventArgs e) { string url = textBox1.Text; string toUrl = Application.StartupPath + "\\" + Path.GetFileName(url); WebClient wc = new WebClient(); wc.DownloadFileCompleted += wc_DownloadFileCompleted; wc.DownloadFileAsync(new Uri(url), toUrl); } void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { MessageBox.Show("下载完成"); }
3、利用缓存下载文件,可以更好的保护硬盘
private void button2_Click(object sender, EventArgs e) { WebClient wc = new WebClient(); wc.OpenReadAsync(new Uri(textBox1.Text)); wc.OpenReadCompleted += wc_OpenReadCompleted; } async void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { await SaveFile(e.Result, Application.StartupPath + "\\" + Path.GetFileName(textBox1.Text)); MessageBox.Show("下载完成"); } else { MessageBox.Show(e.Error.Message); } } Task SaveFile(Stream stream, string savepath) { return Task.Run(() => { var read = stream; byte[] buf = new byte[8192]; int res = 0; FileStream fs = File.Open(savepath, FileMode.OpenOrCreate); using (fs) { while ((res = read.Read(buf, 0, buf.Length)) > 0) { fs.Write(buf, 0, res); fs.Flush(); } } read.Close(); read.Dispose(); }); }
4、上传文件
以上是关于WebClient的使用的主要内容,如果未能解决你的问题,请参考以下文章
WebClient 实现 - 执行这段代码“WebClient.builder().build()”时出现错误
如何在 .NET 6 中用 HttpClient 替换过时的 WebClient
c#利用WebClient和WebRequest获取网页源代码的比较