[英]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.