Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save downloaded files in MemoryStream when using 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();
}

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();
}
like image 834
user1451111 Avatar asked Dec 08 '15 13:12

user1451111


2 Answers

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(); 
     }
}
like image 111
Tjaart Avatar answered Sep 20 '22 16:09

Tjaart


For simple text files, it's even easier:

var contents = sftp.ReadAllText(fileSpec);
like image 30
Jeremy Carter Avatar answered Sep 20 '22 16:09

Jeremy Carter