新手写博客,高手勿喷
最近在学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,