使用C#WebClient类访问(上传/下载/删除/列出文件目录)
在使用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");
//注册下载进度事件通知
_webClient.DownloadProgressChanged += _webClient_DownloadProgressChanged;
//注册下载完成事件通知
_webClient.DownloadFileCompleted += _webClient_DownloadFileCompleted;
//异步下载到D盘
_webClient.DownloadFileAsync(_uri, @"D:\test.xlsx");
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...");
}
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), 0, 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[1024];
int _bytesRead = 0; _bytesRead = _streamReader.Read(_chars, 0, 1024); while (_bytesRead > 0)
{
_stringBuilder.Append(_chars, 0, _bytesRead);
_bytesRead = _streamReader.Read(_chars, 0, 1024);
}
_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 = 0; 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类访问(上传/下载/删除/列出文件目录)的更多相关文章
- 使用C#WebClient类访问(上传/下载/删除/列出文件目录)由IIS搭建的http文件服务器
前言 为什么要写这边博文呢?其实,就是使用C#WebClient类访问由IIS搭建的http文件服务器的问题花了我足足两天的时间,因此,有必要写下自己所学到的,同时,也能让广大的博友学习学习一下. 本 ...
- SpringMVC ajax技术无刷新文件上传下载删除示例
参考 Spring MVC中上传文件实例 SpringMVC结合ajaxfileupload.js实现ajax无刷新文件上传 Spring MVC 文件上传下载 (FileOperateUtil.ja ...
- java FTP 上传下载删除文件
在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...
- [FTP] FTPClient--FTP操作帮助类,上传下载,文件,目录操作 (转载)
点击下载 FTPClient.zip 这个类是关于FTP客户端的操作1.构造函数 2.字段 服务器账户密码3.属性4.链接5.传输模式6.文件操作7.上传和下载8.目录操作9.内容函数看下面代码吧 / ...
- C# FTPClient--FTP操作帮助类,上传下载,文件,目录操作
FROM :http://www.sufeinet.com/forum.php?mod=viewthread&tid=1736&extra=page%3D1%26filter%3Dty ...
- C# WebClient 的文件上传下载
上传文件 string path = openFileDialog1.FileName; WebClient wc = new WebClient(); wc.Credentials = Creden ...
- [C#]工具类—FTP上传下载
public class FtpHelper { /// <summary> /// ftp方式上传 /// </summary> public static int Uplo ...
- FastDFSClient工具类 文件上传下载
package cn.itcast.fastdfs.cliennt; import org.csource.common.NameValuePair; import org.csource.fastd ...
- Win10 搭建FTP环境,并使用Java实现上传,下载,删除
测试的环境一般都是在自己电脑上面装的,现在一般都使用Win10开发 搭建FTP: 第一步:打开控制面板:点击程序 第二步: 第三步: 然后点击确认后等待完成 完成后在启动中找到IIS管理器 打开 在网 ...
随机推荐
- iOS 开发者证书总结 in-house
iOS 证书分两种类型. 第一种为$99美元的,这种账号有个人和公司的区别,公司账号能创建多个子账号,但个人的不能.这种账号可以用来上传app store 第二种为¥299美元的,这种账号只能用于企业 ...
- Android 在闹钟开机时,如何解决开机动画没有播完就进入Launcher M
前言 欢迎大家我分享和推荐好用的代码段~~ 声明 欢迎转载,但请保留文章原始出处: CSDN:http://www.csdn.net ...
- (素材源代码) 猫猫学iOS 之UIDynamic重力、弹性碰撞吸附等现象牛逼Demo
猫猫分享,必须精品 原创文章,欢迎转载. 转载请注明:翟乃玉的博客 地址:http://blog.csdn.net/u013357243 一:效果 二:代码 #import "ViewCon ...
- 如何实现两台Domino之间的相互访问
一)交叉验证 1启动Administrator软件,连接到您的服务器,点击"配置"标签. 2点击右边屏幕"工具"--"验证字"--"交叉验证" 3选择您自己的cert.id,输入其口 ...
- SSM框架中,配置数据库连接的问题
MySQL数据库版本是8.0.11. 要用驱动:com.mysql.cj.jdbc.Driver 最主要的是数据库的连接url. 搞了半天才把问题搞明白: 数据库url后面要加上参数: jdbc:my ...
- Qt5.9静态库编译VS2015-x64
不多说. 编译配置参数如下 configure.bat -static -no-openssl -release 不支持OpenSSL,也没有安装各个数据库的Driver,所以数据库方面也只支持了SQ ...
- Log4Net的应用教程之保存日志到数据库中
关于Log4Net的应用,网上有很多教程,但大多数都是拷贝复制,有些按照他的代码来,运行起来发现也出不来效果,但是Log4net的作用实在是非常大的,或者这里说的不对,应该说系统的日志功能是很重要的也 ...
- 类型“System.Data.SQLite.SQLiteParameter”在未被引用的程序集中定义。必须添加对程序集“System.Data.SQLite, Version=1.0.66.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139”的引用
出现这个问题是 你的系统是64位 同时 dll生成的 any cpu 应该换为 x86
- Iterm2的一些好用法
今天把mac带到公司办公了,爽歪歪啊. 1,如何脱离鼠标拷贝屏幕中的内容 1) Command+f 调出选择框,并在其中输入要复制的字符,可以使用Tab补全 2) 按 Command + c复制字符 ...
- 工作log
整理电脑, 发现这么个文档, 留个纪念... 1. 2016-11-17 ================================ 3.采集任务编制页面,表格表头点击实现升序/降序排列 5.s ...