Reputation: 17388
I am using code like this:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C SomeEXE inputfile.txt";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
process.StartInfo = startInfo;
process.Start();
// Now use streams to capture the output
StreamReader outputReader = process.StandardOutput;
process.WaitForExit();
String line = outputReader.ReadToEnd();
This works fine. However, the issued command (SomeEXE) results in another command prompt being opened which contains the actual results and awaits a carriage return to be closed. Is it possible to obtain this output and issue a carriage return? Thanks.
Upvotes: 0
Views: 169
Reputation: 150108
Launching SomeEXE directly
If you launch SomeEXE directly, rather than via a new command interpreter, your existing code to obtain the output by redirecting stdout to outputReader will work. To do that, change your code as follows:
startInfo.FileName = "SomeEXE";
startInfo.Arguments = "inputfile.txt";
You can redirect stdin to your own stream as well so that you can issue the carriage return:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardinput.aspx
Key points:
myProcess.StartInfo.RedirectStandardInput = true;
StreamWriter myStreamWriter = myProcess.StandardInput;
Write Environment.NewLine to myStreamWriter.
However, since you are not doing that, you are capturing the console of the command interpreter.
If you control SomeEXE's code
If you have control over SomeEXE, you can instruct it to attach to its parent's console:
http://www.csharp411.com/console-output-from-winforms-application/
Note that the MSDN examples show very poor exception handling. They fail to close the streams in the example if an exception is thrown. The easiest way to dispose of the streams is to wrap them in using statements.
If SomeEXE spawns a child process
If you have no control over SomeEXE's code, and SomeEXE is spawning a child process, the task of grabbing stdin/stdout from the grandchild console is harder. However, it can be done.
You need to obtain the process ID of the actual console window in question.
Then, you can use the Win32 API AttachConsole to attach the grandchild process' console to your own.
Upvotes: 4