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

南笙酒味 提交于 2019-12-04 21:32:52

问题


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();
}

回答1:


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()
}



回答2:


For simple text files, it's even easier:

var contents = sftp.ReadAllText(fileSpec);


来源:https://stackoverflow.com/questions/34157735/how-to-save-downloaded-files-in-memorystream-when-using-ssh-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!