Click here to Skip to main content
6,634,665 members and growing! (17,396 online)
Email Password   helpLost your password?
Languages » C# » How To     Intermediate

How to redirect Standard Input/Output of an application

By Manish Ranjan Kumar

This articles demonstrates how to redirect Standard Input/Output of an application.
C# 2.0, Windows, .NET 2.0, WinForms, VS2005, Dev
Posted:27 Apr 2007
Views:49,960
Bookmarked:68 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
32 votes for this article.
Popularity: 6.81 Rating: 4.52 out of 5

1
1 vote, 3.1%
2
4 votes, 12.5%
3
4 votes, 12.5%
4
23 votes, 71.9%
5

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


Member
Graduate from IIT Kharagpur.
Working with Windows forms application for last 3.5 Years.
Currently working with Proteans Software Solutions Bangalore.

Proteans a CAMO group company is an outsourcing company focusing on software product development and business application development on Microsoft Technology Platform. "Committed to consistently deliver high-quality software products and services through continual improvement of our knowledge and practices focused on increased customer satisfaction."
Occupation: Software Developer (Senior)
Company: Proteans
Location: India India

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 24 of 24 (Total in Forum: 24) (Refresh)FirstPrevNext
GeneralHow to simulate the pipe | operator? like "type blabla.txt|abc.exe" Pinmemberatommaki22:21 1 Oct '08  
GeneralNow working when executing application needs an input... Pinmembermasaniparesh2:38 8 Apr '08  
GeneralCan I use this technique to start a process on a server PinmemberSBendBuckeye5:42 18 Oct '07  
GeneralRedirected Standard Output - Problem PinmemberTanushree Paul21:29 5 Sep '07  
Generaluse of redirection opertor PinmemberDurgesh Gupta3:43 13 Aug '07  
GeneralRe: use of redirection opertor Pinmemberdibbs3:12 10 Oct '07  
Generalsbs2003 problem PinmemberDeniroSA4:24 2 Aug '07  
GeneralStandard Input in windows forms? Pinmembersansweb12:15 18 Jul '07  
GeneralVery nice - but ... PinmemberP_R_Sousa3:55 11 Jun '07  
GeneralRe: Very nice - but ... Pinmembertw34ky6:21 14 Jul '07  
Generalcan we pass user defined parameters PinmemberPadoor Shiras21:44 17 May '07  
AnswerRe: can we pass user defined parameters PinmemberManish Ranjan Kumar23:08 17 May '07  
GeneralStandard Input simulation Pinmembernyantoine10:43 16 May '07  
AnswerRe: Standard Input simulation PinmemberManish Ranjan Kumar20:49 16 May '07  
GeneralWhat if the exe need some console input interaction ? Pinmemberwisut22:13 1 May '07  
QuestionMixed output PinmemberYury Goltsman23:07 30 Apr '07  
AnswerRe: Mixed output PinmemberErik Rydgren21:12 1 May '07  
GeneralRe: Mixed output PinmemberYury Goltsman21:30 1 May '07  
GeneralRe: Mixed output PinmemberErik Rydgren22:08 1 May '07  
GeneralRe: Mixed output PinmemberYury Goltsman1:28 2 May '07  
GeneralRe: Mixed output PinmemberMember 17195935:05 8 Feb '08  
GeneralExcellent Pinmembermerlin98110:09 27 Apr '07  
GeneralGood article; one question about arguments... PinmemberPaul C Smith7:03 27 Apr '07  
AnswerRe: Good article; one question about arguments... PinmemberManish Ranjan Kumar7:57 27 Apr '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 27 Apr 2007
Editor: Smitha Vijayan
Copyright 2007 by Manish Ranjan Kumar
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project