【问题标题】:Corrupt zip file while download by URL通过 URL 下载时损坏的 zip 文件
【发布时间】:2011-11-24 17:06:33
【问题描述】:

我从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();
        }

下载时损坏的文件 URL:http://download.geonames.org/export/dump/allCountries.zip

任何人,有同样的问题或可以编写正确上传此 zip 文件的方法??还是我做错了什么??

【问题讨论】:

标签: c# .net zip webclient


【解决方案1】:

如何使用 WebClient.DownloadFile 方法 (WebClient.DownloadFile)

using (var wc = new WebClient())
{
  wc.DownloadFile(Url, ResultFileName);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多