0

I want to read the content in a file which is residing in SFTP using c#. I'm able to fetch the file from the SFTP and download it. I want to read the data in the file without downloading. Could anyone help me on this?

    foreach (var fi in listDirectory)
                {
                    Console.WriteLine(fi.Name);
                    if (fi.Name.Contains(".xml") )
                    {
                        string remoteFileName = fi.Name;
                        using (Stream file1 = File.OpenRead(target + remoteFileName))
                     {                     
                                Console.WriteLine(file1);
}

Thanks.

Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34
sreeprasad k s
  • 53
  • 1
  • 1
  • 9

2 Answers2

0

I do not believe that is possible, in order to have read the content you will by definition have brought the bytes of data locally.

Do you mean you want to avoid saving it to disk? You should be able to download it directly into memory rather than disk, write it to a memory stream instead of a file?

This question has been sat here a long time you've probably found a different solution by now. You could answer your own question now?

SazooCat
  • 150
  • 1
  • 6
0

To read the file as a string you can try this:

using (var sftp = new SftpClient(host, username, password))
            {
                sftp.Connect();
                var files = sftp.ListDirectory(remoteDirectory);
                foreach (var file in files)
                {
                    MemoryStream msStream = new MemoryStream();
                    sftp.DownloadFile(file.FullName, msStream);
                    ReadFile(msStream);
                }
            }

private static void ReadFile(MemoryStream msStream)
        {
            string fileContent = Encoding.UTF8.GetString(msStream.ToArray());
            using (StringReader reader = new StringReader(fileContent))
            {
                string content;
                while ((content = reader.ReadLine()) != null)
                {
                    Console.WriteLine(content);
                }
            }
        }

If you want to read a file as a XML you can use XmlReader class from .NET. It should accept MemoryStream as an input.

SEGMK
  • 130
  • 1
  • 8