Zip file is getting corrupted after downloading from server in C#(在 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 文件损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中从服务器下载后 Zip 文件损坏
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
