How to retrieve file from a foreach statement but using memory stream instead of path(C:\\)

0 votes
asked Apr 18, 2018 by BEGINNERREBEX (150 points)

My objective is to take each file that is in SftpItem item and deserialize the item and place in sql database. My problem arises when trying to retrieve the item out of the for each loop.

private void GetListFinished(Task t) {

        //show error
        if (t.IsFaulted)
            Console.WriteLine("An error occurred: {0}", t.Exception.ToString());

         // show cancel notification
         if (t.IsCanceled)

        SftpItemCollection list = t.Result;

        foreach (SftpItem item in list)

            //open a file in memory

            MemoryStream inMemoryCopy = new MemoryStream();
            using (FileStream msFile = 
Applies to: Rebex SFTP

1 Answer

0 votes
answered Apr 18, 2018 by Lukas Matyska (60,730 points)
selected Apr 19, 2018 by BEGINNERREBEX
Best answer

In your code, you are calling File.OpenRead(item.path), which opens a local file; however, the item instance is of type SftpItem, which represents an item on SFTP server (not local item).

You can download a file from SFTP server into memory like this:

// download a file into memory
MemoryStream inMemoryCopy = new MemoryStream();
client.GetFile(item.Path, inMemoryCopy);

// set position to 0 for further processing (if necessary)
inMemoryCopy.Position = 0;
commented Apr 19, 2018 by BEGINNERREBEX (150 points)
Thank you, so much for your assistance!