[英]How to save downloaded files in MemoryStream when using SSH.NET
I am using SSH.NET library to download files.我正在使用 SSH.NET 库下载文件。 I want to save the downloaded file as a file in memory, rather than a file on disk but it is not happening.
我想将下载的文件保存为内存中的文件,而不是磁盘上的文件,但它没有发生。
This is my code which works fine:这是我的代码,工作正常:
using (var sftp = new SftpClient(sFTPServer, sFTPPassword, sFTPPassword))
{
sftp.Connect();
sftp.DownloadFile("AFile.txt", System.IO.File.Create("AFile.txt"));
sftp.Disconnect();
}
and this is the code which doesn't work fine as it gives 0 bytes stream.这是无法正常工作的代码,因为它提供了 0 字节流。
using (var sftp = new SftpClient(sFTPServer, sFTPPassword, sFTPPassword))
{
sftp.Connect();
System.IO.MemoryStream mem = new System.IO.MemoryStream();
System.IO.TextReader textReader = new System.IO.StreamReader(mem);
sftp.DownloadFile("file.txt", mem);
System.IO.TextReader textReader = new System.IO.StreamReader(mem);
string s = textReader.ReadToEnd(); // it is empty
sftp.Disconnect();
}
You can try the following code, which opens the file on the server and reads it back into a stream:您可以尝试以下代码,它会在服务器上打开文件并将其读回流中:
using (var sftp = new SftpClient(sFTPServer, sFTPUsername, sFTPPassword))
{
sftp.Connect();
// Load remote file into a stream
using (var remoteFileStream = sftp.OpenRead("file.txt"))
{
var textReader = new System.IO.StreamReader(remoteFileStream);
string s = textReader.ReadToEnd();
}
}
对于简单的文本文件,更简单:
var contents = sftp.ReadAllText(fileSpec);
I had a similar issue with the ScpClient
, I needed to reset the stream position to the beginning after downloading the file.我有一个与
ScpClient
类似的问题,我需要在下载文件后将流位置重置为开头。
using (var sftp = new SftpClient(sFTPServer, sFTPPassword, sFTPPassword))
{
sftp.Connect();
System.IO.MemoryStream mem = new System.IO.MemoryStream();
System.IO.TextReader textReader = new System.IO.StreamReader(mem);
sftp.DownloadFile("file.txt", mem);
// Reset stream to the beginning
mem.Seek(0, SeekOrigin.Begin);
System.IO.TextReader textReader = new System.IO.StreamReader(mem);
string s = textReader.ReadToEnd();
sftp.Disconnect();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.