在使用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;
}
}
