[英]C# SFTP - download file corrupted and showing different size when compare the file SFTP server
我正在尝试从 SFTP 服务器下载.zip 和 .xlsx 文件,下载后当我尝试打开 zip 文件时,它说压缩的 zip 文件与 FTP 文件相比文件大小无效并且文件大小也比较高尺寸)。 我正在使用以下代码:
string sFTPHost = "sftphost";
string sFTPDirectory = "file.zip";
string sFTPUser = "username";
string sFTPPassword = "pwd";
string sFTPPort = "22";
ConnectionInfo ConnNfo = new ConnectionInfo(@sFTPHost, Convert.ToInt32(sFTPPort), @sFTPUser,
new AuthenticationMethod[]{
new PasswordAuthenticationMethod(@sFTPUser,@sFTPPassword),
}
);
using (var sftp = new SftpClient(ConnNfo))
{
sftp.Connect();
MemoryStream ms = new MemoryStream();
sftp.DownloadFile(@sFTPDirectory, ms);
byte[] feedData = ms.GetBuffer();
var response = HttpContext.Current.Response;
response.AddHeader("Content-Disposition", "attachment; filename="filename.zip");
response.AddHeader("Content-Length", feedData.Length.ToString());
response.ContentType = "application/octet-stream";
response.BinaryWrite(feedData);
sftp.Disconnect();
}
}
可能是什么问题?
MemoryStream.GetBuffer
返回 stream 的底层数组,该数组可以/将包含已分配的未使用字节。 例如,返回缓冲区的长度将匹配流的当前Capacity
,但很可能大于流的当前Length
。
从文档中:
请注意,缓冲区包含可能未使用的已分配字节。 例如,如果将字符串“test”写入 MemoryStream 对象,则从 GetBuffer 返回的缓冲区长度为 256,而不是 4,其中 252 个字节未使用。
您将需要改用ToArray
。 但是请注意,这会创建一个新数组并将数据复制到其中。
byte[] feedData = ms.ToArray();
var response = HttpContext.Current.Response;
response.AddHeader("Content-Disposition", "attachment; filename=filename.zip");
response.AddHeader("Content-Length", feedData.Length.ToString());
response.ContentType = "application/octet-stream";
response.BinaryWrite(feedData);
或者,您应该能够从一个 stream 复制到另一个:
var response = HttpContext.Current.Response;
response.AddHeader("Content-Disposition", "attachment; filename=filename.zip");
response.AddHeader("Content-Length", ms.Length.ToString());
response.ContentType = "application/octet-stream";
// rewind stream and copy to response
ms.Position = 0;
ms.CopyTo(response.OutputStream);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.