Oct 11 2006

Process.Start and redirect standard output

Posted by admin under .NET

This snippet will show you how to start a command line program - and redirect the output from it to a System.IO.StreamReader. You can then easily read all the output generated from the external program and analyze it or do whatever you please with it:

The example below calls the mysqldump program (for MySQL backup)  which normally dumps the backup data to the console. However we hook into standardoutput by setting  RedirectStandardOutput = true and then read the output by using a regular streamreader.



string sCommand = " -u " + sUserId + " --password=" + sPwd + " mysecretdb ";

//Start exe...
System.Diagnostics.ProcessStartInfo oInfo = new System.Diagnostics.ProcessStartInfo("c:\mysql\mysqldump.exe",sCommand);
oInfo.UseShellExecute = false;
oInfo.ErrorDialog = false;
oInfo.CreateNoWindow = true;
oInfo.RedirectStandardOutput = true;

try
{
	Process p = System.Diagnostics.Process.Start(oInfo);
	System.IO.StreamReader oReader2 = p.StandardOutput;
	string sRes = oReader2.ReadToEnd();
	oReader2.Close();
	//All the external programs output is now in sRes
	//do what we want with it - calling fake function AnalyzeResult
	AnalyzeResult(sRes);
}
catch (Exception ex)
{
	Console.WriteLine(ex.Message);
}