我从http://download.geonames.org/export/dump/下载3(2个zip 1 txt文件)文件,使用WebClient和一个大小为9 Mb的zip文件,当我下载它的大小为215 Mb并且损坏了..我尝试使用WebRequest和FileStream类但又有相同的结果..
我的备用WebClient下载方法:
private void MyDownloadFile(Uri url, string outputFilePath)
{
const int BUFFER_SIZE = 16 * 1024;
using (var outputFileStream = File.Create(outputFilePath, BUFFER_SIZE))
{
var req = WebRequest.Create(url);
using (var response = req.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var buffer = new byte[BUFFER_SIZE];
int bytesRead;
do
{
bytesRead = responseStream.Read(buffer, 0, BUFFER_SIZE);
outputFileStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
}
}
}
}
private void DownloadFile(String Url, String ResultFileName)
{
HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(Url);
HttpWebResponse ws = (HttpWebResponse)wr.GetResponse();
Stream str = ws.GetResponseStream();
byte[] inBuf = new byte[100000];
int bytesReadTotal = 0;
FileStream fstr = new FileStream(ResultFileName, FileMode.Create, FileAccess.Write);
while (true)
{
int n = str.Read(inBuf, 0, 100000);
if ((n == 0) || (n == -1))
{
break;
}
fstr.Write(inBuf, 0, n);
bytesReadTotal += n;
}
str.Close();
fstr.Close();
}
下载时损坏的文件网址:http://download.geonames.org/export/dump/allCountries.zip
任何人,有同样的问题或者可以编写正确上传此zip文件的方法吗?或者我可能做错了什么?
答案 0 :(得分:2)
如何使用WebClient.DownloadFile方法(WebClient.DownloadFile)
using (var wc = new WebClient())
{
wc.DownloadFile(Url, ResultFileName);
}