Sunday, June 7, 2009

Redirect console application output to another application in .NET

In .NET sometime it is required to execute system command and capture its result or data in application that execute that command.
For example you want to execute ipconfig command from .NET application and display its result in window application or need to read output of .NET console application.

For this purpose you need to use Process class that belongs to System.Diagnostics namespace.

//Create process class object
System.Diagnostics.Process p = new System.Diagnostics.Process();

// Set StartInfo property.
// Set redirection true for Error and output stream.
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;

// When you set redirection you must set UseShellExecute to false .
p.StartInfo.UseShellExecute = false;

// Set window style
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

// Set Command paramter.
p.StartInfo.FileName = "ipconfig";
p.StartInfo.Arguments = " /all";

// Set CreateNoWindow to true as window is not required here.
p.StartInfo.CreateNoWindow = true;

// Following two events are new in .NET framework 2.0 which allow us to capture data asynchronously.

p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_ErrorDataReceived);

// Start the process.

// Must call following two methods in order to capture data asynchronously.

// Wait for Process to Exit ( This is not must done ).

// Event Handler for ErrorStream.
void p_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)

// Event Handler for OutputStream.
void p_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)

Even you can use this functionality to make utility like process command background and produce result in window application.

p.StartInfo.FileName = @"%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe";
p.StartInfo.Arguments = @" -v / -f -p C:\Blog\WebSite1 c:\WebSite1Compile";
// Note : Replace %windir% with your window directory. or use p.StartInfo.EnvironmentVariables["windir"]

Above is the one example to compile website application from window application.

Apart from this there is event called Exited associated with Process class object. In order to receive this event you need to set EnableRasingEvents property to true value.

Give your comment and idea on this article.

No comments: