C#中使用WebClient下载指定url的网络照片
生活随笔
收集整理的這篇文章主要介紹了
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的网络照片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#中快速设置控件的相关事件
- 下一篇: VS中调试CS程序时提示:不支持互操作调