博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#文件下载、文件分块下载实例(一)
阅读量:4288 次
发布时间:2019-05-27

本文共 1744 字,大约阅读时间需要 5 分钟。

一、简单下载方式使用WebClient

/// /// 简单下载方式/// 说明:对于大文件的下载,当前处理,会出现假死,长时间之后如果现在成功才相应/// 不能用户断点处理/// public static void Test1(){    //string url = "http://www.imooc.com/video/11555";    string url = "http://v2.mukewang.com/98672526-02b5-454c-b31e-d8526755b40b/L.mp4?auth_key=1474171330-0-0-8ff3fe3a33cfd257577dfa999e41530d";    DateTime start = DateTime.Now;    Uri uri = new Uri(url);    string filename = uri.AbsolutePath.Substring(uri.AbsolutePath.LastIndexOf("/") + 1);    filename = LocalPathHelper.CurrentSolution + "/data/" + filename;    //指定url 下载文件    WebClient client = new WebClient();    client.DownloadFile(url, filename);    Console.WriteLine("下载文件成功,用时:" + (DateTime.Now - start).TotalSeconds + "秒");}

二、分块下载

/// /// 分段下载文件/// 读取速度和分块大小、网速有关/// public static void Test3(){    string url = "http://v2.mukewang.com/98672526-02b5-454c-b31e-d8526755b40b/L.mp4?auth_key=1474171330-0-0-8ff3fe3a33cfd257577dfa999e41530d";    DateTime start = DateTime.Now;    Uri uri = new Uri(url);    string filename = uri.AbsolutePath.Substring(uri.AbsolutePath.LastIndexOf("/") + 1);    filename = LocalPathHelper.CurrentSolution + "/data/" + filename;    //指定url 下载文件    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);    Stream stream = request.GetResponse().GetResponseStream();    //创建写入流    FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);    byte[] bytes = new byte[1024 * 512];    int readCount = 0;    while (true)    {        readCount = stream.Read(bytes, 0, bytes.Length);        if (readCount <= 0)            break;        fs.Write(bytes, 0, readCount);        fs.Flush();    }    fs.Close();    stream.Close();    Console.WriteLine("下载文件成功,用时:" + (DateTime.Now - start).TotalSeconds + "秒");}

更多:

转载地址:http://nfogi.baihongyu.com/

你可能感兴趣的文章
【Spring4揭秘 基础4】国际化--MessageSource
查看>>
Oracle 11g的三个配置文件
查看>>
【深入SpringBoot 第三章】SpringApplicationRunListener及其周期
查看>>
【Spring4揭秘 基础5】BeanDefinition及读取、注册
查看>>
【Spring4揭秘 BeanFactory】基本容器-BeanFactory
查看>>
【Spring4揭秘 BeanFactory】修改BeanFactory-BeanFactoryPostProcessor
查看>>
【Spring4揭秘 BeanFactory】修改Bean---BeanPostProcessor
查看>>
【Spring4揭秘 BeanFactory】PropertyEditor
查看>>
【Spring4揭秘 BeanFactory】InstantiationStrategy和BeanWrapper
查看>>
【Spring4揭秘 BeanFactory】BeanFactory中Bean的实例化过程
查看>>
python3内置函数详解
查看>>
python3标准库
查看>>
python3 标准类型
查看>>
《重构-改善既有代码的设计》总结
查看>>
【Slf4j分析】slf4j-api和slf4j-simple
查看>>
Ruby On Rails总结
查看>>
Oracle数据库中使用java实现存储过程
查看>>
【JDBC4.2】一、JDBC简介
查看>>
【JDBC4.2】二、获取Connection
查看>>
SpringJDBC中DataSource的实现
查看>>