Click here to Skip to main content
Click here to Skip to main content

How to redirect Standard Input/Output of an application

By , 27 Apr 2007
 

Introduction

I 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.

Screenshot - ProcessStartDemo.png

I made use of the Process class in System.Diagnostics which can start a process for you. (Most of the people know about this, but they don't relaize the extent to which it can help). I will explain the process in a step by step manner with code snippets so that you can understand it easily.

Using the code

Step 1 : Create a ProcessStartInfo object. This is used to execute the executable. ProcessStartInfo has three constructors. You can use any one of them, or you can specify the file name and argument at a later stage (but before starting the process).

ProcessStartInfo processStartInfo = 
  new ProcessStartInfo(executableName, executableParameter);
  • executableName is the full path of the executable. If the executable is placed in a location which is registered in the environment variable, you may omit the full path and specify the executable name.
  • executableParameter is the list of parameters to the executable. The application will be launched with these parameters.

Now, by default, the framework invokes the application using Shell Execute. Set the property UseShellExecute to false.You also need to set the ErrorDialog property to false. So why set the UseShellExecute as false? From the MSDN documentation, you can find that, by default, the shell is used to start the process. Now, to capture the input/output/error, we need to create the process directly from the executable. By doing this, if the application is exposing any input/output/error, we can get in that.

processStartInfo.UseShellExecute = false;
processStartInfo.ErrorDialog = false;

Step 2 : Now, the most important thing comes; we need to set the redirecting properties to true. Set it according to your convenience. However, you can use any other application.

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 interest

The code is simple enough to understand. But these are the points which can help you to understand the Process.

  • WaitForExit() function will wait till the application exits.
  • In the demo application, I have not used the input stream. You can use this as well for giving input to the application.
  • Process.Start() method returns a bool value which indicates that the process has been started successfully.
  • Process.ExitCode returns an error code returned by the process. If it is 0, the process exited without error. This may be helpful for the users in some scenario.
  • EnableRaisingEvents property enables you to raise the Exited event. So if you want to make use of the Exited event, make sure to assign it to true.
  • ProcessStartInfo.ErrorDialog allows you to set if an error message will be displayed or not if the process is not started successfully.
  • You can provide a domain name, username, and password for the process in the ProcessStartInfo object.
  • ProcessStartInfo.CreateNoWindow allows you to create a process without creating a window.

History

This 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Manish Ranjan Kumar
Software Developer (Senior) Proteans
India India
Member
Graduate from IIT Kharagpur.
Working with Windows forms application for last 5.5 Years.
Currently working with Meridium Services And Labs, Bangalore.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionCan we run a Java Programme From this Codemembersanjeev46713 Apr '13 - 5:13 
Sir I'm trying to run a java programme and in the ProcessStartInfo method i'm passing the ("java.exe",TextBox2.text) where TextBox2.text contains the java programme when i'm trying to run the programme i'm getting an error which says "Could not find or load main class ". Sir please help.
GeneralMy vote of 5memberrafapucci20 Feb '13 - 6:21 
Nice article and code !
QuestionNeed help on getting output of cdefrag.exemembervantoora28 Jan '13 - 2:18 
Hi, Nice article. I have downloaded the source and compile it directly without modifying the code and launch to test and seems work fine but for some executable only. I said only because I developed an application last year to output of a defragmentation tools from auslogics named...
GeneralGreat article!!memberpetite_paola13 Jul '12 - 1:38 
Thanks a lot. Your code saved my life. It is very useful!!
QuestionReading standard input [modified]memberMember 864852515 Feb '12 - 1:49 
Can you send me the code for reading standard input (not command line argument but input to the secondary process).
Questionreal time shell , not asynchronememberdemotesttest25 Dec '11 - 4:30 
hello I'm having the same problem as many here have : like using ftp.exe or any bidirectional shell exe. I'm using plink.exe : I need in the text box to get output in real time : not just "outputreader.readtoend". Of course I removed the "process waitfor exit". I tried to put a ReadLine...
QuestionCan you help me !memberAll Time Programming16 Feb '11 - 5:36 
Hello Manish,      Thanks for this article. What I want and am loooking for from days is : I am executing from cmd is openvpn --config client.ovpn --ca certificate.cer --auth-user-pass user.txt I don't want to pass user.txt file and enter username and password from the...
QuestionHow to simulate the pipe | operator? like "type blabla.txt|abc.exe"memberatommaki1 Oct '08 - 21:21 
Hello,   Your code is very interesting. I'm looking for a solution of how to simulate the pipe (|) operator. I want to pipe the input to an exe file without using physical file. To do the same as the following command do: type blabla.txt|abc.exe. E.g. the contents of the blabla.txt is...
GeneralNow working when executing application needs an input...membermasaniparesh8 Apr '08 - 1:38 
Hi,   I gone through your code and tried to run to get the input and out of my application but its not working. The code is given below   Process p = new Process(); StreamWriter sw; StreamReader sr; StreamReader err;   ...
QuestionCan I use this technique to start a process on a servermemberSBendBuckeye18 Oct '07 - 4:42 
Hello,   If it is possible to use this technique to start a process on a server, what changes do I need to make? Thanks!   Have a great day!   j2associates_NO_SPAM_@yahoo.com
GeneralRedirected Standard Output - ProblemmemberTanushree Paul5 Sep '07 - 20:29 
Hello everyone,   I am using following lines of code to get the output of a console program which I started from my Win application -   Dim ps As New Process ps.StartInfo.UseShellExecute = False ps.StartInfo.RedirectStandardOutput = True...
Generaluse of redirection opertormemberDurgesh Gupta13 Aug '07 - 2:43 
Can i use redirection operator in the arguments like exe c:\abc.txt < xyz.txt   if not ? How can i do that....? I need to redirect the contents of 1 file to the exe app.   please help me. Thank you.   -Durgesh Gupta
GeneralRe: use of redirection opertormemberdibbs10 Oct '07 - 2:12 
check this. http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=705113&SiteID=1 this might help you  
GeneralRe: use of redirection opertormembervictorbos12 Jun '12 - 2:11 
FYI: Link no longer exists
Generalsbs2003 problemmemberDeniroSA2 Aug '07 - 3:24 
script works fine in XP, but on 2003 when i put in the redirects i get an access denied for the process. please explain how i can get around this, thanks
QuestionStandard Input in windows forms?membersansweb18 Jul '07 - 11:15 
I was curious if you could use this approach to pipe messages to child application that is a Windows form?   It was my understanding that there is no standard input in a windows form. I have a parent project which I would like to open files in another application that I have written. The...
GeneralVery nice - but ...memberP_R_Sousa11 Jun '07 - 2:55 
Very nice article, but I can't get it to work with Windows ftp.exe For some reason it hangs on reading standard-input Can anyone explain me why   TIA  
GeneralRe: Very nice - but ...membertw34ky14 Jul '07 - 5:21 
Yeah, acknowledged same problem here. I have the same issue with psftp.exe or pscp.exe.   Once your process is waiting for input, the last line in the streamreader, usually a prompt or something, isn't a complete line. Therefore it isn't returned yet by the reader and the thread blocks...
Questioncan we pass user defined parametersmemberPadoor Shiras17 May '07 - 20:44 
can we pass user defined parameters to the calling executable. i mean if calling executable is named as XYZ.exe. and from my executing assembly i want to pass 3 user defined parameters, let it be Database Connection string. how do i achieve this. first of all is this possible. i dont want it to...
AnswerRe: can we pass user defined parametersmemberManish Ranjan Kumar17 May '07 - 22:08 
Yes you can do this thing. The assembly is calling some other assembly and it wants to paas some user defined data to the called assembly. This can be achieved using the Input stream. Capture input stream and write the parameters required to the stream. Please let me know if it does not helps.
GeneralStandard Input simulationmembernyantoine16 May '07 - 9:43 
Hi, Great article! In my app, I need to simulate the standard input with parameters taken from the c# code. How can I do that? Thanks
AnswerRe: Standard Input simulationmemberManish Ranjan Kumar16 May '07 - 19:49 
Hi capture the standard input stream and write the parameter there. If u are having any problem let me know i will provide source for that.
QuestionWhat if the exe need some console input interaction ?memberwisut1 May '07 - 21:13 
Some exe need runtime input from console. How can I adapt your code to do thing (like put the cmd.exd window in my rich editbox) ?
QuestionMixed outputmemberYury Goltsman30 Apr '07 - 22:07 
If my application executes following code: Console.Error.WriteLine("err1"); Console.Out.WriteLine("out1"); Console.Error.WriteLine("err2"); Console.Out.WriteLine("out2");standard console shows following output: out1 err1 out2 err2but your method separates output and error streams:...
AnswerRe: Mixed outputmemberErik Rydgren1 May '07 - 20:12 
Use the same stream for both std output and std error.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 27 Apr 2007
Article Copyright 2007 by Manish Ranjan Kumar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid