I am trying to execute command prompt lines after connecting to remote unix server from a C# code. I have used the below code and which is working. However, I want the commands to execute completely before the next command line is taken. currently the execution of lines is faster and due to this, the result which I am getting is wrong.
Each command should complete the processing and then move to next command. In my C# web application, I have the below code on a button click event
SshClient sshclient = new SshClient(hostname, username, pwd);
sshclient.Connect();
ShellStream stream = sshclient.CreateShellStream("cmsd", 80, 24, 800, 600, 1024);
objclass.sendCommand("command1", stream).ToString();
objclass.sendCommand("command2", stream).ToString();
The class file contains the methods as below:
public StringBuilder sendCommand(string customCMD, ShellStream stream)
{
StringBuilder answer = new StringBuilder();
answer.Clear();
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
WriteStream(customCMD, writer, stream);
answer = ReadStream(reader);
return answer;
}
private void WriteStream(string cmd, StreamWriter writer, ShellStream stream)
{
writer.WriteLine(cmd);
while (stream.Length == 0)
{
Thread.Sleep(500);
}
}
private StringBuilder ReadStream(StreamReader reader)
{
StringBuilder result = new StringBuilder();
string line;
while ((line = reader.ReadLine()) != null)
{
result.AppendLine(line);
}
return result;
}
//Tried new code
public StringBuilder sendCommand(string customCMD, ShellStream stream)
{
StringBuilder answer = new StringBuilder();
answer.Clear();
answer.Length = 0;
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
writer.AutoFlush = true;
while (!stream.DataAvailable)
{
WriteStream(customCMD, writer, stream);
Thread.Sleep(5000);
}
answer = ReadStream(reader);
return answer;
}