WebClient 从服务器下载/获取文件方式

第一种:使用 WebClient 自封装方法: DownloadFile(); 下载方便、直接。

/// <summary>/// 下载文件(WebClient.DownloadFile)/// </summary>/// <param name="downFileUrl">下载文件链接地址</param>/// <param name="savePath">保存路径</param>/// <returns></returns>public static string DownLoadFileByWebClientStatic(string downFileUrl, string savePath){string result = string.Empty;try{WebClient wcClient = new WebClient();wcClient.DownloadFile(downFileUrl, savePath);result = "下载成功";}catch (WebException ex){result = $"下载失败!Error={ ex.Message}";}return result;}/// <summary>/// 下载文件(wcClient.DownloadFileAsync)/// </summary>/// <param name="downFileUrl">下载文件链接地址</param>/// <param name="savePath">保存路径</param>/// <returns></returns>public static string DownLoadFileMethod(string downFileUrl, string savePath){string result = string.Empty;try{WebClient wcClient = new WebClient();wcClient.DownloadDataCompleted += (t, s) =>{result = "下载成功";//不会直接返回(无状态?)};wcClient.DownloadFileAsync(new Uri(downFileUrl), savePath);}catch (WebException ex){result = $"下载失败!Error={ ex.Message}";}return result;}

第二种:使用读取文件流形式下载/获取文件。(自测通过)

///
/// 下载文件(Stream 形式处理)
///
/// 下载文件链接地址
/// 保存路径
///
public static string DownLoadFileByWebClient(string downFileUrl, string savePath)
{
string result = string.Empty;
try
{
WebClient wcClient = new WebClient();

        WebRequest webReq = WebRequest.Create(downFileUrl);WebResponse webRes = webReq.GetResponse();long fileLength = webRes.ContentLength;Stream srm = webRes.GetResponseStream();StreamReader srmReader = new StreamReader(srm);byte[] bufferbyte = new byte[fileLength];int allByte = (int)bufferbyte.Length;int startByte = 0;while (fileLength > 0){int downByte = srm.Read(bufferbyte, startByte, allByte);if (downByte == 0) break;startByte += downByte;allByte -= downByte;}//检测保存文件所在目录是否存在if (!File.Exists(savePath)){string[] dirArray = savePath.Split('\\');string temp = string.Empty;for (int i = 0; i < dirArray.Length - 1; i++){temp += dirArray[i].Trim() + "\\";if (!Directory.Exists(temp))Directory.CreateDirectory(temp);}}using (FileStream fsSave = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write)){fsSave.Write(bufferbyte, 0, bufferbyte.Length);fsSave.Dispose();}//与using 方法两者等同。//FileStream fs = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write);//fs.Write(bufferbyte, 0, bufferbyte.Length);srm.Close();srmReader.Close();//fs.Close();result = $"下载成功 path={savePath}";}catch (WebException ex){result = $"下载失败!Error={ ex.Message}";}return result;
}

第二种 通过文件流 下载,方法分支:(使用WebClient 的 OpenRead() 方式获取到Stream ,然后进行文件流读取,不知为何,自测失败,下载的文件无法正常打开)。 现在还没有找到合理解释,希望大家评论。  
///
/// 下载文件
///
/// 资源URL
/// 保存根目录/目录
///
public string DownFileByStream(string URLAddress, string saveBasePath)
{
string result = string.Empty;
try
{
WebClient client = new WebClient();
Stream str = client.OpenRead(URLAddress);
StreamReader reader = new StreamReader(str);

            byte[] bytes = new byte[1024 * 1024];//自定义大小 1Mint allybytes = (int)bytes.Length;int startbytes = 0;while (allybytes > 0){int m = str.Read(bytes, startbytes, allybytes);  //获取当前读取字节位置if (m == 0)break;startbytes += m;allybytes -= m;}reader.Dispose();str.Dispose();string path = saveBasePath + System.IO.Path.GetFileName(URLAddress);FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);fsWrite.Write(bytes, 0, startbytes);fsWrite.Flush();fsWrite.Close();result = "下载成功!";}catch (Exception ex){result = "下载失败!" + ex.Message;}return result;}

本文转载自:https://www.cnblogs.com/skyheaving/p/12499629.html

WebClient 从服务器下载/获取文件方式相关推荐

  1. 云服务器中获取文件代码,从云服务器中获取文件

    从云服务器中获取文件 内容精选 换一换 登录Windows操作系统的弹性云服务器时,需使用密码方式登录.因此,用户需先根据创建弹性云服务器时使用的密钥文件,获取该弹性云服务器初始安装时系统生成的管理员 ...

  2. 华为服务器上传文件,云服务器上传文件方式

    云服务器上传文件方式 内容精选 换一换 安装传输工具在本地主机和Windows云服务器上分别安装数据传输工具,将文件上传到云服务器.例如QQ.exe.在本地主机和Windows云服务器上分别安装数据传 ...

  3. IIS服务器下载apk文件

    IIS服务器下载apk文件设置 需要新增MIME映射: application/vnd.android.package-archive apk

  4. 跨服务器上传文件方式

    跨服务器上传文件的方式有很多,其中一种是使用在中间服务器上使用临时文件的方式进行保存后再发送到另一个服务器上,实现文件上传. 问题点:中间保存临时文件,还需要不定时的进行文件清理,比较麻烦 直接进行文 ...

  5. 使用.net FtpWebRequest 实现FTP常用功能 上传 下载 获取文件列表 移动 切换目录 改名 ....

    平时根本没时间搞FTP什么的,现在这个项目需要搞FTP,为什么呢,我给大家说下项目背景,我们的一个应用程序上需要上传图片,但是用户部署程序的服务器上不让上传任何东西,给了我们一个FTP账号和密码,让我 ...

  6. 网易云服务器下载.txt文件工具

    下载工具 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import j ...

  7. java从服务器下载xls文件到客户端

    查考网上的代码写了一个下载xls文件到客户端的jsp页面,只要将服务器的文件地址传给这个jsp页面就可以实现下载文件到客户端了. Code: <%@ page language="ja ...

  8. android m4a播放器下载,Android 上传m4a格式音频 本地文件和从服务器下载的文件有差异 一般会有哪些因素导致?...

    这是我本地文件的二进制显示, 00000: 000000186674797069736F6D00000000 00010: 69736F6D33677034000002F36D6F6F76 00020 ...

  9. linux服务器不允许下载文件,关于从Linux服务器下载Excel文件的问题

    本地下载文件可以,可是把代码放到Linux服务器下载下来的是jsp页面内容,下载的Excel文件中的内容则是jsp中展示的内容 相关代码 response.setCharacterEncoding(& ...

最新文章

  1. oracle中的数据集合操作
  2. linux中find命令列举,Linux中常见find命令的使用
  3. C语言实现通用链表初步(二)
  4. linux下nginx启动停止重启控制脚本
  5. jQuery length和size()区别
  6. mysql升序nuul在最后,javaweb连接数据库并完成增删改查
  7. 专访死马:为什么说Egg.js是企业级Node框架
  8. SQL Agent服务无法启动如何破
  9. 揭秘Mindscape WPF Elements 5新特性
  10. Python 求水仙花数
  11. matlab仿真元件,matlab电力系统仿真元件[高等教育]
  12. 封神:人在朝歌,皇宫签到六十年
  13. 如何剔除数组中得空字符串 null undefined
  14. svn process exited with error code: 1
  15. 一个女留学生在美国的七年(转载)
  16. matlab蒙特卡罗方法求体积_蒙特卡罗方法详细讲解与MATLAB实现.ppt
  17. MXNet对DenseNet(稠密连接网络)的实现
  18. ASEMI大功率场效应管和三极管的区别
  19. 30个免费且很棒的公共数据源分享
  20. 基,特征向量和基础解系

热门文章

  1. FoveaBox:Beyond Anchor-based Object Detector
  2. 反距离加权法高程_GIS中的反距离加权法插值算法
  3. 取整(JSU-ZJJ)
  4. java sql2016驱动_微软发布用于SQL Server 的JDBC 6.0驱动下载 - IT之家
  5. round函数怎么用oracle,oracle round函数的使用方法
  6. 计算主义质疑(Query Algorithmism)
  7. Linux音频转换工具包sox
  8. MMoE ESSM PLE对比
  9. 2022速卖通宠物用品热销及需求品类推荐!
  10. 使用一个月后,苹果 M1 MacBook Pro 深度体验报告