|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionI was working in a project, and I needed to start a secondary process from an application and pass from the application, the needed parameters and inputs to the secondary process and also capture all possible output and errors from the secondary process. I also did not want the exceptions and crashes from the secondary process to be directly displayed to the user. This article briefly expalins how I achieved this. I had to control the standard input, standard output, and the standard error of the secondary process. Here is an example of my code in action. The shutdown proces is invoked from my application, and it displays the output from the process. As we did not provide an option or parameter for the secondary process, it captures the standard output and displays it.
I made use of the Using the codeStep 1 : Create a ProcessStartInfo processStartInfo =
new ProcessStartInfo(executableName, executableParameter);
Now, by default, the framework invokes the application using Shell Execute. Set the property processStartInfo.UseShellExecute = false;
processStartInfo.ErrorDialog = false;
Step 2 : Now, the most important thing comes; we need to set the redirecting properties to processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
Step 3 : Now that things are done, we are ready to capture the input/output/error. Start the process. Process process = new Process();
process.StartInfo = processStartInfo;
bool processStarted = process.Start();
Step 4 : Capture the input /output /error streams for your use. Note that the input stream is a writer. For giving input, you need to write the input string in the input stream. StreamWriter inputWriter = process.StandardInput;
StreamReader outputReader = process.StandardOutput;
StreamReader errorReader = process.StandardError;
process.WaitForExit();
Step 5: You are done; use the streams as needed. Points of interestThe code is simple enough to understand. But these are the points which can help you to understand the
HistoryThis is the first release of the code. Modifications and feature enhancements will be done on requests. I request users to mail me directly to my email address for any suggestions. In this demo, I have not used the input stream; if you are having trouble with it, then message me and I will provide a sample for that also.
|
||||||||||||||||||||||