C#使用WebClient实现上传下载

作者:springsnow 时间:2022-04-22 21:46:31 

一、概述

System.Net.WebClient属于高层类、使用简单。均支持异步版本。支持http,https,fpt,files等URI。

建议不要将 WebClient 类用于新的开发。Net4.5及以上请改用 System.Net.Http.HttpClient 类。

二、下载

1、OpenRead:打开一个可读的Stream。

对于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;

2、DownloadData:以byte[]形式下载资源。

byte[] data= client.DownloadData(serverUri):

3、DownloadFile:将资源下载在本地文件。

void client.DownloadFile(serverUri,localFile):

4、DownloadString:以string的形式下载资源。

string content =client.DownloadString(serverUri):

5、事件

  • DownloadProgressChanged事件:

  • Download***Completed事件

6、获取下载网址的真实文件名

获取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;

三、上传

1、OpenWrite:打开一个可写的流。

对于FTP资源,默认使用STOR命令;对于HTTP资源,默认使用POST方法。

Strean =client.OpenWrite(serverUri);

2、UploadData:将byte[]数据上传到serverUri。

byte[] =client.UploadData(serverUri,byte[]);

3、UploadFile:将本地文件上传到serverUri。

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;
}

4、UploadValues:将指定的名/值集合到serverUri。

byte[] =client.UploadValues(serverUri,namevalueCollection);

5、事件:

  • UploadProgressChanged:e.ProcessPercentage,e.TatalBytesToReceive,e.BytesReceived;

  • Upload***Completed: e.Cancelled,e.Error,E.UserState;

四、System.Url类(统一资源表示符)

Uri url=new Uri(”//www.jb51.net:2105/article/247999.htm?order=true”);

  • OriginalString 获取传递给 Uri 构造函数的原始 URI 字符串。//www.jb51.net:2105/article/247999.htm?order=true

  • Scheme 获取此 URI 的方案名称。http

  • IsFile 获取一个值,该值指示指定的 Uri 是否为文件 URI。false

  • Host 获取此实例的主机部分。www.jb51.net

  • HostNameType 获取 URI 中指定的主机名的类型。DNS

  • Port 获取此 URI 的端口号。2105

  • IsDefaultPort 获取一个值,该值指示 URI 的端口值是否为此方案的默认值。false

  • AbsolutePath 获取 URI 的绝对路径。/article/247999.htm

  • Query 获取指定 URI 中包括的任何查询信息。?order=true

  • PathAndQuery 获取用问号 (?) 分隔的 AbsolutePath 和 Query 属性。/article/247999.htm?order=true

来源:https://www.cnblogs.com/springsnow/p/9433995.html

标签:C#,WebClient,上传,下载
0
投稿

猜你喜欢

  • Android Studio打包.so库到apk中实例详解

    2022-06-25 19:19:25
  • 如何从dump文件中提取出C#源代码

    2022-09-13 19:54:54
  • java中MultipartFile互转File的方法

    2022-12-14 16:52:09
  • C#迷你猜数实例分析

    2023-11-02 16:10:49
  • Java SpringBoot Validation用法案例详解

    2023-10-21 15:06:49
  • Struts2修改上传文件大小限制方法解析

    2023-02-22 21:13:19
  • IKAnalyzer结合Lucene实现中文分词(示例讲解)

    2022-10-13 03:24:44
  • Dwr3.0纯注解(纯Java Code配置)配置与应用浅析二之前端调用后端

    2023-08-19 17:32:33
  • java读取properties文件的方法

    2021-12-25 11:30:36
  • spring boot validation参数校验实例分析

    2023-02-03 02:50:38
  • Android音视频开发之MediaExtactor使用教程

    2023-03-20 19:25:11
  • 解析Tars-Java客户端源码

    2023-04-08 01:18:39
  • Java中ArrayList类的用法与源码完全解析

    2023-07-22 02:32:49
  • 使用java基础类实现zip压缩和zip解压工具类分享

    2021-11-23 08:03:41
  • java实现人员信息管理系统

    2023-11-02 05:21:31
  • Android7.0 MessageQueue详解

    2021-08-29 17:01:43
  • C#字典Dictionary的用法说明(注重性能版)

    2023-08-05 19:33:02
  • 全面解读C#编程中的析构函数用法

    2021-05-24 00:27:33
  • 详解mybatis插入数据后返回自增主键ID的问题

    2021-09-04 19:08:00
  • C# WinForm中Panel实现用鼠标操作滚动条的实例方法

    2021-08-08 01:52:42
  • asp之家 软件编程 m.aspxhome.com