在 C# 中从服务器下载后 Zip 文件损坏

Zip file is getting corrupted after downloading from server in C#(在 C# 中从服务器下载后 Zip 文件损坏)
本文介绍了在 C# 中从服务器下载后 Zip 文件损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

request = MakeConnection(uri, WebRequestMethods.Ftp.DownloadFile, username, password);
response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();

//This part of the code is  used to write the read content from the server
using (StreamReader responseReader = new StreamReader(responseStream))
{
    using (var destinationStream = new FileStream(toFilenameToWrite, FileMode.Create))
    {
        byte[] fileContents = Encoding.UTF8.GetBytes(responseReader.ReadToEnd());
        destinationStream.Write(fileContents, 0, fileContents.Length);
    }
}

//This part of the code is  used to write the read content from the server
using (var destinationStream = new FileStream(toFilenameToWrite, FileMode.Create))
{
    long length = response.ContentLength;
    int bufferSize = 2048;
    int readCount;
    byte[] buffer = new byte[2048];
    readCount = responseStream.Read(buffer, 0, bufferSize);
    while (readCount > 0)
    {
        destinationStream.Write(buffer, 0, readCount);
        readCount = responseStream.Read(buffer, 0, bufferSize);
    }
}

前者将内容写入文件,但当我尝试打开文件时,它说它已损坏.但是后者在下载 zip 文件时完美地完成了这项工作.之前的代码对 zip 文件不起作用,因为它对文本文件非常有效,是否有任何具体原因?

The former ones writes the content to the file but when I try to open the file it says it is corrupted. But the later one does the job perfectly when downloading zip files. Is there any specific reason why the former code doesn't work for zip files as it works perfectly for text files?

推荐答案

byte[] fileContents = Encoding.UTF8.GetBytes(responseReader.ReadToEnd());

您尝试将二进制 PDF 文件解释为 UTF-8 文本.那是行不通的.

You try to interpret a binary PDF file as an UTF-8 text. That just cannot work.

有关正确代码,请参阅在 C#/.NET 中向/从 FTP 服务器上传和下载二进制文件.

For a correct code, see Upload and download a binary file to/from FTP server in C#/.NET.

这篇关于在 C# 中从服务器下载后 Zip 文件损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)