Reading cmd output line at a time

Dec 7, 2011 at 12:52 AM

i am new to C Sharp and .net , i like this SSH.NET API. i was able to connect to SSH and run a command with few hundred lines of output. i am now trying to figure out how to read the cmd.Result one line at a time and load the output into a List<string> array so that i can sort through the output...  i am currenlty using .net code to run an extenral process to plink.exe (putty cli) and i can use stdout from it and load stdout into the List<string> array line at a time, then later i am able to sort the List<string> array....  i am just having hard time finding a way to read cmd.Result one line at a time or is there another method i should use, any help or suggestions???  during debug i can check cmd.Result and i see all of my output from the command the hundreds of lines :)

Coordinator
Dec 7, 2011 at 1:20 AM

Hi,

You can use OutputStream property to read the result.

For example:

                var cmd = ssh.CreateCommand("ls -l");
                cmd.Execute();
                var read = cmd.OutputStream.Read(buffer, 0, 1024);

Hope it helps.

 

Thanks,

Oleg

Dec 7, 2011 at 9:01 PM

 

 Ok, i could not figure out outputstream it seemed to be centered around characters or bytes, sorry not a skilled a programmer as you are :), nice api... so i gave up and did it this way, i am running several commands and parsing output using a string array , so to get rid of having to use process to plink.exe this was easiest way to incorporate your api into my code, it works well. thanks.

var cmd = client.CreateCommand("term len 0");
cmd.Execute();
cmd.Execute(
"command_whatever"
);
string test = new string (cmd.Result.ToArray());
string[] test2 = test.Split('\n'

);

 

Dec 8, 2011 at 6:33 PM

Thanosazlin, try using a String Reader for this:

 

using (System.IO.StringReader sr = new System.IO.StringReader(multilineString))
{
	string line;
	while ((line = sr.ReadLine()) != null)
	{
		// process line here
	}
}

// using statement automatically closes StringReader

 

When you get a little further into your development, try turning this into an Extension Method:

public static IEnumerable<string> ReadLineByLine(this string multilineString)
{
    using (System.IO.StringReader sr = new System.IO.StringReader(multilineString))
    {
        string line;
        while ((line = sr.ReadLine()) != null)
        {
            yield return line;
        }
    }
}