欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

C#中使用WebClient下载指定url的网络照片

发布时间:2025/3/19 57 豆豆
生活随笔 收集整理的这篇文章主要介绍了 C#中使用WebClient下载指定url的网络照片 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

场景

效果

 

方法

DownloadFile(Uri, String)
将具有指定 URI 的资源下载到本地文件。

public void DownloadFile (Uri address, string fileName);
参数
address
Uri
以 String 形式指定的 URI,将从中下载数据。
fileName
String
要接收数据的本地文件的名称。


官方文档

https://docs.microsoft.com/zh-cn/dotnet/api/system.net.webclient.downloadfile?redirectedfrom=MSDN&view=netframework-4.8#overloads

实现

构建图片下载url

这里本地运行Tomcat后,构建图片的url

http://localhost:8080/tomcat.png

 

这样就可以访问本地实现图片的url了。

自己可以另行寻找url。

实现

设计窗体如下

 

在按钮的点击事件中编写:

 private void btnDownload_Click(object sender, EventArgs e){try{WebClient webClient = new WebClient();//判断文件是否存在if (!File.Exists("dingdang.png")){//下载文件webClient.DownloadFile("http://localhost:8080/tomcat.png", "dingdang.png");}//将指定路径的图片显示在窗体中picShow.Image = Image.FromFile("dingdang.png");}catch(Exception ex){MessageBox.Show(ex.ToString());}}

完整代码

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Net; using System.IO;namespace WebClientDemo {public partial class WebClientDemoForm : Form{public WebClientDemoForm(){InitializeComponent();}private void btnDownload_Click(object sender, EventArgs e){try{WebClient webClient = new WebClient();//判断文件是否存在if (!File.Exists("dingdang.png")){//下载文件webClient.DownloadFile("http://localhost:8080/tomcat.png", "dingdang.png");}//将指定路径的图片显示在窗体中picShow.Image = Image.FromFile("dingdang.png");}catch(Exception ex){MessageBox.Show(ex.ToString());}}} }

示例代码下载

https://download.csdn.net/download/badao_liumang_qizhi/11545922

总结

以上是生活随笔为你收集整理的C#中使用WebClient下载指定url的网络照片的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。