System.Net.WebClient属于高层类、使用简单。均支持异步版本。支持http,https,fpt,files等URI。
建议不要将
WebClient
类用于新的开发。Net4.5及以上请改用 System.Net.Http.HttpClient 类。
对于FTP资源,默认使用RETR命令;对于HTTP资源,默认使用Get方法。
Stream= client.OpenRead(serverUri):
举例
WebClient client = new WebClient(); client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); client.Encoding = Encoding.GetEncoding("gb2312"); client.Credentials = new NetworkCredential("csp", "welcome"); Stream data = client.OpenRead(url);//OpenRead为下载的数据打开一个只读的流 StreamReader reader = new StreamReader(data, Encoding.GetEncoding("gb2312")); sting s = reader.ReadToEnd(); reader.Close(); return s;
byte[] data= client.DownloadData(serverUri):
void client.DownloadFile(serverUri,localFile):
string content =client.DownloadString(serverUri):
获取http头部信息的内容。
Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。
Content-disposition其实可以控制用户请求所得的内容存为一个文件的时候提供一个默认的文件名,文件直接在浏览器上显示或者在访问时弹出文件下载对话框。
形如:”Content-Disposition: attachment;filename=FileName.txt“。
当你在响应类型为application/octet- stream情况下使用了这个头信息的话,那就意味着你不想直接显示内容,而是弹出一个"文件下载"的对话框
WebClient client = new WebClient(); byte[] data = client.DownloadData(fileUrl); var mc = Regex.Matches(Server.UrlDecode(client.ResponseHeaders["Content-Disposition"]), @"filename=(.+)"); string filename = mc[0].Groups[1].Value;
对于FTP资源,默认使用STOR命令;对于HTTP资源,默认使用POST方法。
Strean =client.OpenWrite(serverUri);
byte[] =client.UploadData(serverUri,byte[]);
byte[] =client.UploadFile(serverUri,localFile);
举例:
WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; client.Credentials = new NetworkCredential("csp", "welcome"); client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback); client.UploadFileCompleted += new UploadFileCompletedEventHandler(UploadFileCompletedCallback); client.UploadFileAsync(new Uri(uriString + Path.GetFileName(localfileName)), null, localfileName, progressbarfrom); /// /// 上传过程处理 /// /// /// private static void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e) { (e.UserState as ProgressBar).Value = e.ProgressPercentage; } private static void UploadFileCompletedCallback(object sender, UploadFileCompletedEventArgs e) { if (e.Error == null) MessageBox.Show("完成上传"); else throw e.Error; }
byte[] =client.UploadValues(serverUri,namevalueCollection);
Uri url=new Uri(”//www.qb5200.com:2105/article/247999.htm?order=true”);
到此这篇关于C#使用WebClient实现上传下载的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。