一聚教程网:一个值得你收藏的教程网站

热门教程

C#中WebClient实现文件下载实现方案

时间:2022-06-25 08:16:08 编辑:袖梨 来源:一聚教程网

功能:从特定的URI请求文件(.Net FrameWork目前支持http:、https:和file:标识符开头的URI)。

特点:功能比较简单。

用法:

1、使用WebClient下载文件。

范例一:使用WebClient下载文件,并保存到硬盘上(需要引入System.Net命名空间)。

 代码如下 复制代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
 
namespace Test
{
  class Program
  {
    static void Main(string[] args)
    {
      WebClient client = new WebClient();
      //如果需要下载权限则需要添加下面的权限代码
       //client.Credentials = new NetworkCredential(loginName, loginPwd);
      client.DownloadFile(new Uri("http://www.111com.net/"), "d://webClient.html");
    }
  }
}

范例二;使用OpenRead()方法返回一个Stream引用。然后把数据提取到内存中(也可调用OpenWrite方法返回一个可写数据流不演示)。

 代码如下 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
 
namespace Test
{
  class Program
  {
    static void Main(string[] args)
    {
      WebClient client = new WebClient();
      using (Stream sw = client.OpenRead("http://www.111com.net/"))
      {
        using (StreamReader sr = new StreamReader(sw))
        {
          while (sr.ReadLine() != null)
          {
            Console.WriteLine(sr.ReadLine());
            Console.ReadKey();
          }
        }
      }
    }
  }
}

2、使用WebClient上传文件。

可以使用UpLoadFile函数和UpLoadData函数分别上传文件二进制数据。

但是WebClient不能提供身份验证证书,许多站点都不接受没有身份认证的验证证书。


那我们要如何C#实现获取程序实时下载速度

首先,在下载文件的时候,我们不用DownloadFile()方法进行下载,用WebResponse的GetResponseStream()流进行下载,设一个临时储存变量用来保存不断接收的数据。再用一个额外的独立计时器来分别根据时间间隔和临时收到数据量做计算,临时数据接收量在速度计算后会清空。

下面开始代码:

 代码如下 复制代码

string FileTemp=null;                                      //临时储存
private const int SPD_INTERVAL_SEC = 1;                    //时间常量
Stream stream = rps.GetResponseStream();                   //获取服务器响应文件流
byte[] byts = new byte[rps.ContentLength];                 //创建字节数组保存文件流
System.Threading.Timer FileTm = new System.Threading.Timer(SpeedTimer, null, 0, SPD_INTERVAL_SEC*1000);//使用回调函数,每SPD_INTERVAL_SEC秒执行一次
while ((count = stream.Read(byts, 0, 5000)) != 0)
{
 FileTemp += count;      //临时储存长度
 strTemp += count;       //获取已下载文件长度
}
///
///回调方法
///
private void SpeedTimer(object state)
 {
 FileSpeed = FileTemp/SPD_INTERVAL_SEC;   //SPD_INTERVAL_SEC秒下载字节数,
 FileTemp = 0;                            //清空临时储存
 }

整个文件流全部保存在byts字节数组中,可以在循环时,边读边写入。
效果图:
20130314220237jquery164029858965225584155="86" loaded="true" original="https://img.111cn.net/uploads/20220926/img_633171dc9190f30.png" />

热门栏目