使用C#WebClient类访问(上传/下载/删除/列出文件目录)
在使用WebClient类之前,必须先引用System.Net命名空间,文件下载、上传与删除的都是使用异步编程,也可以使用同步编程,
这里以异步编程为例:
1)文件下载:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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)文件上传:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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)文件删除:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | 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; } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
2017-01-09 ADO.NET对象模型
2017-01-09 趣味理解ADO.NET对象模型
2017-01-09 C# ToString格式大全
2017-01-09 C#中A a=new B()的意义
2017-01-09 sql中时间的一些特殊转换