簡體   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