关于WebClient的遇到的问题
来源:互联网 发布:水洗标制作软件 编辑:程序博客网 时间:2024/06/14 19:51
新手写博客,高手勿喷
最近在学xamarin相关的知识,有部分是文件的下载,本来用FTPWebRequest和FTPWebResponse可以解决的,发现使用WebClient的代码更加的少,所以就试试
但是下载的文件永远是0B,最开始以为是xamarin不支持WebClient,自己新建一个C#项目也出现了这个问题,网上也发现有人出现同样的问题。
点击打开链接
public void DownloadFile(Uri address, string fileName) { if (Logging.On) { Logging.Enter(Logging.Web, this, "DownloadFile", address + ", " + fileName); } if (address == null) { throw new ArgumentNullException("address"); } if (fileName == null) { throw new ArgumentNullException("fileName"); } WebRequest request = null; FileStream writeStream = null; bool flag = false; this.ClearWebClientState(); try { writeStream = new FileStream(fileName, FileMode.Create, FileAccess.Write); request = this.m_WebRequest = this.GetWebRequest(this.GetUri(address)); this.DownloadBits(request, writeStream, null, null); flag = true; } catch (Exception exception) { if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException)) { throw; } if (!(exception is WebException) && !(exception is SecurityException)) { exception = new WebException(SR.GetString("net_webclient"), exception); } AbortRequest(request); throw exception; } finally { if (writeStream != null) { writeStream.Close(); if (!flag) { System.IO.File.Delete(fileName); } writeStream = null; } this.CompleteWebClientState(); } if (Logging.On) { Logging.Exit(Logging.Web, this, "DownloadFile", ""); } }
底层是调用WebRequest来完成下载的,HttpWebRequest和FtpWebRequest都继承自WebRequest,所以WebClient可以完成http、ftp等协议的下载,观察代码可知,方法的FileStream在开始部分就已经有了,所以调用该方法就一定会生成文件,只不过后面没有完成stream的写入工作,这就导致了最终的文件是0B,至于什么原因,求大神解释,现在没有时间看详细的代码了
<span style="font-family: Arial, Helvetica, sans-serif;">解决方法:最好是使用DownloadData来完成文件的下载,与downloadFile的方式大致一样,在下载完成后处理e.Result来写入到本地</span>
<span style="color:#ff0000;">另外:</span>C#中并不是所有的Stream都支持获取length和position,读取本地文件的流能够获取,但是读取的是网络流,会提示NotSupportOperation,
0 0
- 关于WebClient的遇到的问题
- WebClient的使用问题
- 关于WebClient超时问题
- 关于webClient 上传文件的总结
- WebClient的超时问题及解决
- WebClient的超时问题及解决
- WebClient的超时问题及解决
- WebClient的超时问题及解决
- httpWebRequest WebClient下载慢的问题处理
- 关于css遇到的问题
- 关于混编遇到的问题
- 关于cocoapods遇到的问题
- 关于&& || ! 遇到的一个问题
- 关于mklink遇到的问题
- 关于QString遇到的问题
- 关于C#中WebClient调用REST服务,缓存问题的解决方案
- 使用WebClient下载AssetBundles时遇到问题
- WebClient的研究笔记(一)--认识WebClient
- Java虚拟机工作原理详解
- javascript中得in运算符
- windows下比较比较好用的git客户端有2种
- 企业架构之应用控制器
- ubuntu12.04LTS 桌面卡死的解决方法
- 关于WebClient的遇到的问题
- 要打开项目中的某文件各种路径表示方式
- HDU2577 How to Type【DP】
- 数码管的动态显示0~f
- 使用ScriptEngineManager解析json
- TortoiseGit(乌龟git)保存用户名密码的方法
- iOS第三方开源库的吐槽和备忘
- 企业架构之页面控制器
- 在vs2012中搭建一个ironpython运行环境