Ok, first some background information. I wrote an application for connecting in real time to cmd.exe
Problem:
Instead of writing once in Process, I want to write several times without closing cmd.exe. This leads to an error, because I need to close StreamWriter before you can get any output, and after receiving the result, I want to write to it again.
Example:
I want to give a command cd C:\and get the result with a modified path. After that, I want to see what files are in the C: \ directory using dir. I do not want the process to restart because it resets the path.
I know I can just use it dir C:\, but it’s not. This is just a brief example; I want to use this for many other things that need to be addressed.
class Program
{
static void Main(string[] args)
{
ProcessStartInfo pInfo = new ProcessStartInfo();
pInfo.RedirectStandardInput = true;
pInfo.RedirectStandardOutput = true;
pInfo.RedirectStandardError = true;
pInfo.UseShellExecute = false;
pInfo.CreateNoWindow = true;
pInfo.FileName = "cmd.exe";
Process p = new Process();
p.StartInfo = pInfo;
bool pStarted = false;
Console.Write("Command: ");
string command = Console.ReadLine();
while (command != "exit")
{
if (!pStarted && command == "start")
{
p.Start();
Console.WriteLine("Process started.");
pStarted = true;
}
else if (pStarted)
{
StreamWriter sWriter = p.StandardInput;
if (sWriter.BaseStream.CanWrite)
{
sWriter.WriteLine(command);
}
sWriter.Close();
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
Console.WriteLine("\n" + output + "\n");
}
Console.Write("\nCommand: ");
command = Console.ReadLine();
}
Console.WriteLine("Process terminated.");
Console.ReadKey();
}
}
Does anyone know how I can hold onto a process and write to it several times, each time getting a conclusion.
Thanks in advance.
Edit: This may or may not be slightly identical to the following question: Run multiple commands with the same process using .NET . The related question has no useful answer and differs in different ways. One huge problem that I am facing is that I want the result to be printed after every command the user sent.
source
share