How to save downloaded files to MemoryStream when using SSH.NET

I use the SSH.NET library to upload files. I want to save the downloaded file as a file in memory, not a file on disk, but this does not happen.

This is my code that works great:

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 code that doesn't work fine, as it gives a stream of 0 bytes.

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();
}
+4
source share
2 answers

You can try the following code, which opens the file on the server and reads it back into the 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()
}
+5
source

For simple text files, this is even simpler:

var contents = sftp.ReadAllText(fileSpec);
-1
source

Source: https://habr.com/ru/post/1619042/


All Articles