本文介紹了在 C# 中從服務器下載后 Zip 文件損壞的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
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 文件損壞的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!