Search code examples
c#ftpsftpwinscpwinscp-net

Read file content from SFTP location using WinSCP


I need to read a file from SFTP location using WinSCP .NET assembly in C#. I'm able to download file from SFTP location to local path and read it. But is there a way to read the file content directly without downloading to local path?

Below is the code used for downloading. But I see no option available to read the file content directly in WinSCP... something like using response, stream etc...

TransferOptions objTransferoptions = new Transferoptions()
objTransferoptions.transfermode = Automatic
Session objsession = new Session()
objsession.Open()
objsession.GetFiles(remotepath, localpath, false,objTransferoptions)

Can someone please let me know, if it is possible to read file contents directly from SFTP location? Thanks in advance!


Solution

  • Use Session.GetFile to download a remote file to memory.

    using (Session session = new Session())
    {
        // Connect
        session.Open(sessionOptions);
         
        using (var stream = session.GetFile(remotePath))
        {
            // now process the data in "stream" the same way you would
            // for example process a stream returned by System.IO.File.Open()
        }
    }