Zip file is getting corrupted after downloading from server in C#
1
2 3 4 5 6 7 8 9 10 11 12 13 |
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 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //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 文件不起作用,因为它对文本文件非常有效,是否有任何具体原因?
1
|
byte[] fileContents = Encoding.UTF8.GetBytes(responseReader.ReadToEnd());
|
您尝试将二进制 PDF 文件解释为 UTF-8 文本。那是行不通的。
有关正确的代码,请参阅使用 C#/.NET 向/从 FTP 服务器上传和下载二进制文件。
这是对我有用的解决方案
C#
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public IActionResult GetZip([FromBody] List<DocumentAndSourceDto> documents) { List<Document> listOfDocuments = new List<Document>(); foreach (DocumentAndSourceDto doc in documents) using (var ms = new MemoryStream()) using (var fileStream = new FileStream(attachment.FilePath, FileMode.Open)) } throw new ErrorException("Can’t zip files"); |
不要错过这里的
使用 BinaryWriter 并将其传递给 FileStream.
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
//This part of the code is used to write the read content from the server
using (var destinationStream = new BinaryWriter(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); } } |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/269764.html