繁体   English   中英

c#WebClient下载一个邮编会损坏它

[英]c# WebClient Downloading a Zip Corrupts it

对我来说,使用webclient下载Zip文件似乎无法正常工作,一旦下载并保存了该zip文件,则显示该文件无效或已损坏,并使用zip阅读器打开。 但是源zip文件似乎很好,它是有效的zip。

下载代码:

using (WebClient webClient = new WebClient())
        {
            webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
            webClient.DownloadFileAsync(new Uri(URL), downloadZipFilename);
        }
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        progressBar.Value = e.ProgressPercentage;
    }

    private void Completed(object sender, AsyncCompletedEventArgs e)
    {
        //unzip
        using (ZipFile zipFile = ZipFile.Read(currentTemporaryDownloadFileUrl))
        {
            zipFile.ExtractAll(currentTargetFileUrl);
        }
        File.Delete(currentTemporaryDownloadFileUrl);
        DownloadFinished(this,EventArgs.Empty);
        Console.WriteLine("File finished downloading.");
    }

zip提取内容显示为已损坏。

服务器代码:

 //send file
                    e.Response.Connection.Type = HttpServer.Headers.ConnectionType.Close;
                    byte[] buffer = ReadFile(filePath);
                    e.Response.Body.Write(buffer, 0, buffer.Length);

服务器上的读取文件:

public static byte[] ReadFile(string filePath)
        {
            // this method is limited to 2^32 byte files (4.2 GB)

            FileStream fs = File.OpenRead(filePath);
            try
            {
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
                fs.Close();
                return bytes;
            }
            finally
            {
                fs.Close();
            }
        }

怎么了

谢谢克里斯蒂安·斯图尔特

WebClient调用中,您使用downloadZipFilename而在使用Completed方法时,使用currentTemporaryDownloadFileUrl ... ...可能是因为Completed方法试图解压缩其他文件和已下载的文件吗?

您的服务器代码仅支持<= 2 GB(Int32是带符号的int的别名!)...文件是否可能大于2 GB? 如果文件更大,则您的服务器代码会将所有“剩余”(大于2 GB)的字节发送为0x00,这肯定会使ZIP损坏...

而不是效率低下的将ZIP文件加载到内存中,然后将其写出,如何使用

e.Response.TransmitFile(filePath);

TransmitFile流无需缓冲即可直接流向输出流,从而最大程度地减少了内存消耗。

我建议您将服务器传输与客户端拆包解耦。 这样,您可以隔离出现的任何问题。

确保服务器“创建并传输zip文件”功能正常。 尝试从浏览器访问服务器,确保可以成功解压缩该zip文件。 然后添加C#客户端,以编程方式下载并解压缩zip文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM