WebClient上传下载文件,小白篇
WebClient的上传文件一直报错,各种百度各种稀奇古怪的东西,终于百度到一篇小白学习篇
转自: https://www.cnblogs.com/cncc/p/5722231.html
使用C#WebClient类访问(上传/下载/删除/列出文件目录)由IIS搭建的http文件服务器
前言
为什么要写这边博文呢?其实,就是使用C#WebClient类访问由IIS搭建的http文件服务器的问题花了我足足两天的时间,因此,有必要写下自己所学到的,同时,也能让广大的博友学习学习一下。
本文足如有不足之处,请在下方留言提出,我会进行改正的,谢谢!
搭建IIS文件服务器
本博文使用的操作系统为Windows 10 企业版,其他Windows系统类似,请借鉴:
一、当然,开始肯定没有IIS,那该怎么办?需要一个软件环境进行搭建,具体方法如下:
1)打开“控制面板”,找到“程序与功能”,如下图所示:
2)点进去之后,找到“启用或关闭Windows功能”,如下图所示:
3)点进去之后,将“Internet Information Services”下所有节点都打勾(这样就搭建了一个功能完全的HTTP/FTP服务器),注意“WebDAV发布”必须要安装,这个跟文件服务器中文件访问权限有着很大的关系,如果想对服务器中某个具有读写权限的文件夹进行读写,就必须开启该选项,如下图所示:
4)等待安装完毕,请耐心等待, 如下图所示:
5)完成之后,点击“关闭”按钮即可,然后,打开“控制面板”,找到“管理工具”,如下图所示:
6)点击“管理工具”后,找到“Internet Information Services (IIS)管理器”,打开它,如下图所示:
7)进去之后,就已经进入了IIS的管理界面,我们只用到的功能为红色框内的IIS功能,如下图所示:
8)第一搭建IIS,会出现一个默认的Web网站,我们将鼠标移到“Default Web Site”上方,右键弹出菜单,在菜单中点击“删除”将该网站删除,如下图所示:
9)添加自己的一个网站,鼠标移到“网站”上方,右键点击鼠标,弹出菜单,在菜单中点击“添加网站”,如下图所示:
10)根据如下图所说的步骤,填写网站名称及选择物理路径,其他默认即可,然后点击“确定”按钮:
11)本网站仅作为文件服务器,因此,将服务器的文件浏览功能打开,以便浏览,具体操作为鼠标双击“目录浏览”后,将“操作”一栏里的“启用”打开,如下图所示:
12)鼠标双击“WebDAV创作规则”,如下图所示:
13)点击“WebDAV设置”,如下图所示:
14)将①②所示红色框内的属性设置为图中所示的属性,并点击“应用”,如下图所示:
15)返回到“WebDAV创作规则”,点击“添加创作规则”,如下图所示:
16)在弹出的“添加创作规则”,将“允许访问此内容”选中,权限“读取、源、写入”都打勾,点击“确定”按钮关闭,如下图所示:
17)返回到“WebDAV创作规则”,点击“启用WebDAV”,如下图所示:
18)双击“身份验证”,将“匿名身份验证”(客户端读取文件)及“Windows身份验证”(客户端写入、删除)启用,如下所示:
19)为了能让文件服务器具有写入、删除功能,可以在现有Windows系统账户上新建一个隶属于“Power Users”的账户“test”(密码:123),如下图所示:
以上关于如何创建账户的内容,请自行百度
20)为了能让test账户顺利访问存放于E盘下的“TestWebSite”文件夹,需要为该文件夹设置Power Users组的访问权限,如下图所示:
关于如何将特定组或用户设置权限的问题,请自行百度
21)查看本机IIS的IP地址,并在浏览器输入该IP,将会显示以下内容,如下图所示:
22)自此,IIS文件服务器的搭建已经完毕。
使用C#WebClient访问IIS文件服务器
本博文使用的的IDE为VS2015,在使用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", "");
- //上传的链接地址(文件服务器)
- 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", "");
- //待删除的文件链接地址(文件服务器)
- Uri _uri = new Uri(@"http://192.168.1.103/test.doc");
- //注册删除完成时的事件(模拟删除)
- _webClient.UploadDataCompleted += _webClient_UploadDataCompleted;
- //异步从文件(模拟)删除文件
- _webClient.UploadDataAsync(_uri, "DELETE", new byte[]);
- Console.ReadKey();
- }
- //删除完成事件处理程序
- private static void _webClient_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
- {
- Console.WriteLine("Deleted...");
- }

运行结果如下:
4)列出文件(或目录):
需引入命名空间:System.IO、System.Xml及System.Globalization

- static void Main(string[] args)
- {
- SortedList<string, ServerFileAttributes> _results =GetContents(@"http://192.168.1.103", true);
- //在控制台输出文件(或目录)信息:
- foreach(var _r in _results)
- {
- Console.WriteLine($"{_r.Key}:\r\nName:{_r.Value.Name}\r\nIsFolder:{_r.Value.IsFolder}");
- Console.WriteLine($"Value:{_r.Value.Url}\r\nLastModified:{_r.Value.LastModified}");
- Console.WriteLine();
- }
- Console.ReadKey();
- }
- //定义每个文件或目录的属性
- struct ServerFileAttributes
- {
- public string Name;
- public bool IsFolder;
- public string Url;
- public DateTime LastModified;
- }
- //将文件或目录列出来
- static SortedList<string, ServerFileAttributes> GetContents(string serverUrl, bool deep)
- {
- HttpWebRequest _httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(serverUrl);
- _httpWebRequest.Headers.Add("Translate: f");
- _httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
- string _requestString = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
- @"<a:propfind xmlns:a=""DAV:"">" +
- "<a:prop>" +
- "<a:displayname/>" +
- "<a:iscollection/>" +
- "<a:getlastmodified/>" +
- "</a:prop>" +
- "</a:propfind>";
- _httpWebRequest.Method = "PROPFIND";
- if (deep == true)
- _httpWebRequest.Headers.Add("Depth: infinity");
- else
- _httpWebRequest.Headers.Add("Depth: 1");
- _httpWebRequest.ContentLength = _requestString.Length;
- _httpWebRequest.ContentType = "text/xml";
- Stream _requestStream = _httpWebRequest.GetRequestStream();
- _requestStream.Write(Encoding.ASCII.GetBytes(_requestString), , Encoding.ASCII.GetBytes(_requestString).Length);
- _requestStream.Close();
- HttpWebResponse _httpWebResponse;
- StreamReader _streamReader;
- try
- {
- _httpWebResponse = (HttpWebResponse)_httpWebRequest.GetResponse();
- _streamReader = new StreamReader(_httpWebResponse.GetResponseStream());
- }
- catch (WebException ex)
- {
- throw ex;
- }
- StringBuilder _stringBuilder = new StringBuilder();
- char[] _chars = new char[];
- int _bytesRead = ;
- _bytesRead = _streamReader.Read(_chars, , );
- while (_bytesRead > )
- {
- _stringBuilder.Append(_chars, , _bytesRead);
- _bytesRead = _streamReader.Read(_chars, , );
- }
- _streamReader.Close();
- XmlDocument _xmlDocument = new XmlDocument();
- _xmlDocument.LoadXml(_stringBuilder.ToString());
- XmlNamespaceManager _xmlNamespaceManager = new XmlNamespaceManager(_xmlDocument.NameTable);
- _xmlNamespaceManager.AddNamespace("a", "DAV:");
- XmlNodeList _nameList = _xmlDocument.SelectNodes("//a:prop/a:displayname", _xmlNamespaceManager);
- XmlNodeList _isFolderList = _xmlDocument.SelectNodes("//a:prop/a:iscollection", _xmlNamespaceManager);
- XmlNodeList _lastModifyList = _xmlDocument.SelectNodes("//a:prop/a:getlastmodified", _xmlNamespaceManager);
- XmlNodeList _hrefList = _xmlDocument.SelectNodes("//a:href", _xmlNamespaceManager);
- SortedList<string, ServerFileAttributes> _sortedListResult = new SortedList<string, ServerFileAttributes>();
- ServerFileAttributes _serverFileAttributes;
- for (int i = ; i < _nameList.Count; i++)
- {
- if (_hrefList[i].InnerText.ToLower(new CultureInfo("en-US")).TrimEnd(new char[] { '/' }) != serverUrl.ToLower(new CultureInfo("en-US")).TrimEnd(new char[] { '/' }))
- {
- _serverFileAttributes = new ServerFileAttributes();
- _serverFileAttributes.Name = _nameList[i].InnerText;
- _serverFileAttributes.IsFolder = Convert.ToBoolean(Convert.ToInt32(_isFolderList[i].InnerText));
- _serverFileAttributes.Url = _hrefList[i].InnerText;
- _serverFileAttributes.LastModified = Convert.ToDateTime(_lastModifyList[i].InnerText);
- _sortedListResult.Add(_serverFileAttributes.Url, _serverFileAttributes);
- }
- }
- return _sortedListResult;
- }

运行结果如下:
WebClient上传下载文件,小白篇的更多相关文章
- webclient上传下载文件
定义WebClient使用的操作类: 操作类名称WebUpDown WebClient上传文件至Ftp服务: //// <summary> /// WebClient上传文件至Ftp服务 ...
- C#实现http协议支持上传下载文件的GET、POST请求
C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...
- WebSSH画龙点睛之lrzsz上传下载文件
本篇文章没有太多的源码,主要讲一下实现思路和技术原理 当使用Xshell或者SecureCRT终端工具时,我的所有文件传输工作都是通过lrzsz来完成的,主要是因为其简单方便,不需要额外打开sftp之 ...
- rz和sz上传下载文件工具lrzsz
######################### rz和sz上传下载文件工具lrzsz ####################################################### ...
- WebClient上传音频文件
//WebClient上传音频文件 public string UploadVoice(string fileNamePath) { Voice model=new Voice(); string s ...
- linux上很方便的上传下载文件工具rz和sz
linux上很方便的上传下载文件工具rz和sz(本文适合linux入门的朋友) ##########################################################&l ...
- shell通过ftp实现上传/下载文件
直接代码,shell文件名为testFtptool.sh: #!/bin/bash ########################################################## ...
- SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例
本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...
- linux下常用FTP命令 上传下载文件【转】
1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码,分别输入用户名和相应密码 ...
随机推荐
- Java中的享元设计模式,涨姿势了!
首先来看一段代码: public class ShareTest { public static void main(String[] args) { Integer a = 127; ...
- equals与== 和toString方法
/** * equals()方法的使用 * * 1.java.lang.Object类中的equals()方法的定义: * * public boolean equals(Object obj) { ...
- C++ Primer: 1. 初识输入和输出
C++没有定义任何的输入和输出语句,而是使用了 标准库来提供IO机制---iostream; 标准库iostream定义了4种不同的IO对象: cin: 标准输入对象:instream类型的对 ...
- 文件的三种打开方式及with管理文件上下文
文件的三种打开方式及with管理文件上下文 一.文件的三种打开方式 1.1 只读 f = open(r'D:\pycharm\yjy\上海python学习\456.txt','r',encoding= ...
- mysql小数和类型转换函数
保留两位小数 SELECT ROUND( 123456789.3563898,2),TRUNCATE(123456789.3563898,2),FORMAT(123456789.3563898,2); ...
- 扇形导航 css3
本篇文章将通过对css3中的2d变化以及过渡进行分析设计 先放上最终效果图 功能实现:1.给扇形home元素设置点击事件并添加2d旋转 2.给导航栏设置2d旋转 并通过 ...
- jquery preventDefault() 方法防止打开不是本站的链接URL
将以下代码保存为test.html,用浏览器打开即可测试 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN&q ...
- JS获取当前日期和时间的方法,并按照YYYY-MM-DD格式化
Js获取当前日期时间及其它操作 var myDate = new Date(); myDate.getYear(); //获取当前年份(2位) myDate.getFullYear(); ...
- VMware导入ova报错
报错如下: 此主机支持Intel VT-x,但Intel VT-x处于禁用状态. 解决方案如下: 联想E75主机,重启按F1进入BIOS Advanced—>CPU setup—>In ...
- Mac SIP系统完整性保护如何关闭
方法/步骤1: 打开Mac终端输入命令:csrutil status 它会显示关闭的话是disable,开启的话是enabled.默认情况下是开启的所以要关闭. 方法/步骤2: 点击桌面的apple ...