Zip文件从C#服务器下载后被损坏 [英] Zip file is getting corrupted after downloading from server in C#

查看:192
本文介绍了Zip文件从C#服务器下载后被损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

要获得正确的代码,请参阅上载和下载二进制文件到/从FTP服务器在C#/。NET

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆