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 文件,而它适用于文本文件?
byte[] fileContents = Encoding.UTF8.GetBytes(responseReader.ReadToEnd());
您尝试将二进制 PDF 文件解释为 UTF-8 文本。那是行不通的。
正确的代码请参见在 C#/.NET 中向 FTP 服务器上传和下载二进制文件 https://stackoverflow.com/q/44606028/850848.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)