How to return data line by line - WeOnlyDo Discussion board

How to return data line by line (wodSSH / wodSSH.NET)

by Ernesto Cullen, Wednesday, November 19, 2014, 12:26 (3440 days ago)

Hi
I have to process a command on a remote linux machine that will return a lot of text (think 'ls -alR /'). If I use ssh.Execute it returns all data as a string which is killing my memory, and in fact I need to process it line by line so I want to return the data that way. I tried several variations on following code, all gave me some text and then block completely until timeout. What am I doing wrong?

Thanks in advance,

Ernesto



  ...
  String partialData = String.Empty;

  ssh.DataReceivedEvent += (sender, args) =>
  {
     ssh.Timeout = 0;
     while (true)
     {
       try
       {
         var tempString = ((SSH) sender).PeekLine();
         ((SSH)sender).Receive(tempString.Length);
         if (partialData.Length > 0)
         {
           var s = partialData + tempString;
           action(s);
           partialData = String.Empty;
         }
         else
         {
           action(tempString);
         }
       }
       catch (Exception ex)
       {
         //receive whats left of the buffer, waiting for the next batch
         var partialString = ((SSH) sender).Receive();
         partialData += partialString;
         break;
       }
     }
     ssh.Timeout = timeout;
   };

  ssh.Connect(hostname, port);
  ...

Action<String> action is a delegate that will be called to send each line.


Complete thread: