Blog Post

使用C#WebClient类访问(上传/下载/删除)由IIS搭建的http文件服务器

搭建IIS文件服务器

一、当然,开始肯定没有IIS,那该怎么办?需要一个软件环境进行搭建,具体方法如下:

不啰嗦了 问度娘 O(∩_∩)O哈哈哈~

安装完成之后,跟着走(一Windows server 2008 为例)

1

2

3

4

5

6

7

8

9

10

11

12

13如果刚开始没有绑定ip的现在可以绑定

使用C#WebClient访问IIS文件服务器

在使用WebClient类之前,必须先引用System.Net命名空间,文件下载、上传与删除的都是使用异步编程,也可以使用同步编程,

这里以异步编程为例:

/* 需要注意的是 路径一定要写全 尤其是服务器端的路径 (带文件名后缀的,一开始没写坑死了)*/

1)文件下载:

static void Main(string[] args)

{

//定义_webClient对象

WebClient _webClient = new WebClient();

//使用默认的凭据——读取的时候,只需默认凭据就可以

_webClient.Credentials = CredentialCache.DefaultCredentials;

//下载的链接地址(文件服务器)

Uri _uri = new Uri(@"http://192.168.1.103/test.doc");

//注册下载进度事件通知

_webClient.DownloadProgressChanged += _webClient_DownloadProgressChanged;

//注册下载完成事件通知

_webClient.DownloadFileCompleted += _webClient_DownloadFileCompleted;

//异步下载到D盘

_webClient.DownloadFileAsync(_uri, @"D:\test.doc");

Console.ReadKey();

}

//下载完成事件处理程序

private static void _webClient_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)

{

Console.WriteLine("Download Completed...");

}

//下载进度事件处理程序

private static void _webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)

{

Console.WriteLine($"{e.ProgressPercentage}:{e.BytesReceived}/{e.TotalBytesToReceive}");

}

2)文件上传:

static void Main(string[] args)

{

//定义_webClient对象

WebClient _webClient = new WebClient();

//使用Windows登录方式

_webClient.Credentials = new NetworkCredential("test", "123");

//上传的链接地址(文件服务器)

Uri _uri = new Uri(@"http://192.168.1.103/test.doc");

//注册上传进度事件通知

_webClient.UploadProgressChanged += _webClient_UploadProgressChanged;

//注册上传完成事件通知

_webClient.UploadFileCompleted += _webClient_UploadFileCompleted;

//异步从D盘上传文件到服务器

_webClient.UploadFileAsync(_uri,"PUT", @"D:\test.doc");

Console.ReadKey();

}

//下载完成事件处理程序

private static void _webClient_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)

{

Console.WriteLine("Upload Completed...");

}

//下载进度事件处理程序

private static void _webClient_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)

{

Console.WriteLine($"{e.ProgressPercentage}:{e.BytesSent}/{e.TotalBytesToSend}");

}

3)文件删除:

static void Main(string[] args)

{

//定义_webClient对象

WebClient _webClient = new WebClient();

//使用Windows登录方式

_webClient.Credentials = new NetworkCredential("test", "123");

//待删除的文件链接地址(文件服务器)

Uri _uri = new Uri(@"http://192.168.1.103/test.doc");

//注册删除完成时的事件(模拟删除)

_webClient.UploadDataCompleted += _webClient_UploadDataCompleted;

//异步从文件(模拟)删除文件

_webClient.UploadDataAsync(_uri, "DELETE", new byte[0]);

Console.ReadKey();

}

//删除完成事件处理程序

private static void _webClient_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)

{

Console.WriteLine("Deleted...");

}