场景
效果
方法
DownloadFile(Uri, String)
将具有指定 URI 的资源下载到本地文件。
public void DownloadFile (Uri address, string fileName);
参数
address
Uri
以 String 形式指定的 URI,将从中下载数据。
fileName
String
要接收数据的本地文件的名称。
官方文档
实现
构建图片下载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