前言

为什么要写这边博文呢?其实,就是使用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;
}

运行结果如下:

使用C#WebClient类访问(上传/下载/删除/列出文件目录)由IIS搭建的http文件服务器的更多相关文章

  1. 使用C#WebClient类访问(上传/下载/删除/列出文件目录)

    在使用WebClient类之前,必须先引用System.Net命名空间,文件下载.上传与删除的都是使用异步编程,也可以使用同步编程, 这里以异步编程为例: 1)文件下载: static void Ma ...

  2. SpringMVC ajax技术无刷新文件上传下载删除示例

    参考 Spring MVC中上传文件实例 SpringMVC结合ajaxfileupload.js实现ajax无刷新文件上传 Spring MVC 文件上传下载 (FileOperateUtil.ja ...

  3. java FTP 上传下载删除文件

    在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...

  4. [FTP] FTPClient--FTP操作帮助类,上传下载,文件,目录操作 (转载)

    点击下载 FTPClient.zip 这个类是关于FTP客户端的操作1.构造函数 2.字段 服务器账户密码3.属性4.链接5.传输模式6.文件操作7.上传和下载8.目录操作9.内容函数看下面代码吧 / ...

  5. C# FTPClient--FTP操作帮助类,上传下载,文件,目录操作

    FROM :http://www.sufeinet.com/forum.php?mod=viewthread&tid=1736&extra=page%3D1%26filter%3Dty ...

  6. C# WebClient 的文件上传下载

    上传文件 string path = openFileDialog1.FileName; WebClient wc = new WebClient(); wc.Credentials = Creden ...

  7. [C#]工具类—FTP上传下载

    public class FtpHelper { /// <summary> /// ftp方式上传 /// </summary> public static int Uplo ...

  8. FastDFSClient工具类 文件上传下载

    package cn.itcast.fastdfs.cliennt; import org.csource.common.NameValuePair; import org.csource.fastd ...

  9. Win10 搭建FTP环境,并使用Java实现上传,下载,删除

    测试的环境一般都是在自己电脑上面装的,现在一般都使用Win10开发 搭建FTP: 第一步:打开控制面板:点击程序 第二步: 第三步: 然后点击确认后等待完成 完成后在启动中找到IIS管理器 打开 在网 ...

随机推荐

  1. Uva10207 The Unreal Tournament

    题目链接戳这里 首先递归调用函数次数其实是可以预处理出来的,但是这里我们介绍一个更屌的做法. 设\(F(i,j)\)为求解\(P(i,j)\)所遍历的节点数目,则有\[F(0,j)=F(i,0)=0\ ...

  2. [转贴]JAVA 百度地图SDK地图学习——实现定位功能

    之前已经完成了百度地图SDK和百度定位SDK的配置. http://my.oschina.net/u/1051634/blog/180880 实现百度定位的功能,最好仔细看看官方的文档,看了好几次才有 ...

  3. nginx+gunicorn

    wsgi接口,使用gunicorn作为server,想在外层加nginx. 配置了 proxy_pass   http://127.0.0.1:9008; 访问报301. 参考gunicorn 官网配 ...

  4. 【HDOJ】1983 Kaitou Kid - The Phantom Thief (2)

    不仅仅是DFS,还需要考虑可以走到终点.同时,需要进行预处理.至多封闭点数为起点和终点的非墙壁点的最小值. #include <iostream> #include <cstdio& ...

  5. Three ways to do WCF instance management

    Three ways to do WCF instance management (Per call, Per session, and Single). IntroductionVery often ...

  6. Set up JBPM5.4 Final Installer to use MS SQL Server 2008 using JTDS(转)

    [-] A What I Am Going To Do B The Setup Steps C Lets Install it   A. What I Am Going To Do B. The Se ...

  7. Cocos2d-x 坑之一:Xcode文件真实目录与工程视图目录

    Cocos2d-x一定要保证 Xcode文件真实目录与工程视图目录 的一致性,不然,会出现文件读取不了,或include不了的情况. 如果出现此类情况,优先查看真实目录的结构.

  8. HDU-1390 Binary Numbers

    http://acm.hdu.edu.cn/showproblem.php?pid=1390 Binary Numbers Time Limit: 2000/1000 MS (Java/Others) ...

  9. [转]NHibernate之旅(6):探索NHibernate中的事务

    本节内容 事务概述 1.新建对象 [测试成功提交] [测试失败回滚] 2.删除对象 3.更新对象 4.保存更新对象 结语 上一篇我们介绍了NHibernate中的Insert, Update, Del ...

  10. ajax向后台传值

    function save_person(){ //保存个人信息编辑 var data = getFormJson(".row"); //获取表单数据 $.post(clerk_u ...