使用SSH.NET时如何在MemoryStream中保存下载的文件 [英] How to save downloaded files in MemoryStream when using SSH.NET
本文介绍了使用SSH.NET时如何在MemoryStream中保存下载的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用SSH.NET库下载文件.我想将下载的文件另存为内存中的文件,而不是磁盘上的文件,但这没有发生.
I am using SSH.NET library to download files. 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();
}
这是无法正常工作的代码,因为它提供了0个字节的流.
and this is the code which doesn't work fine as it gives 0 bytes stream.
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
var remoteFileStream = sftp.OpenRead("file.txt");
System.IO.TextReader textReader = new System.IO.StreamReader(remoteFileStream);
string s = textReader.ReadToEnd();
sftp.Disconnect()
}
这篇关于使用SSH.NET时如何在MemoryStream中保存下载的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文