12.10. Launching and Interacting with Console Utilities
Problem
You have an application that you need to automate and that takes input only from the standard input stream. You need to drive this application via the commands it will take over the standard input stream.
Solution
Say we needed to drive the cmd.exe application to display the current time with the TIME /T command (it is possible to just run this command from the command line, but this way we can demonstrate an alternative method to drive an application that responds to standard input). The way to do this is to launch a process that is looking for input on the standard input stream. This is accomplished via the Process class StartInfo property, which is an instance of a ProcessStartInfo class. The Process. Start method will launch a new process, but the StartInfo property controls many of the details of what sort of environment that process executes in.
First, make sure that the StartInfo.RedirectStandardInput property is set to true. This setting notifies the process that it should read from standard input. Then, set the StartInfo.UseShellExecute property to false, because if you were to let the shell launch the process for you, it would prevent you from redirecting standard input.
Once this is done, launch the process and write to its standard input stream as shown in Example 12-1.
Example 12-1. RunProcessToReadStdIn method
public static void RunProcessToReadStandardInput() { Process application = new Process(); // Run the ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access