Monday, June 7, 2010

Using Tasks to Redirect Output from Spawned Process

Here’s a small trick I found useful. I recently wrote a tool that performs an ‘xcopy’ backup of the source files in my visual studio projects directory. The tool is a command line application that spawns a few other command line applications (xcopy for one) and redirects their output to its own standard output. Since some spawned processes are long running, I want to show their output as they run, I created a static method that does it all using the Task class from the .Net 4 framework.

Code Snippet
  1. static int SpawnAndRedirect(string command, string args)
  2. {
  3.     Process process;
  4.     ProcessStartInfo processStartInfo;
  5.     processStartInfo = new ProcessStartInfo(command, args);
  6.     processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  7.     processStartInfo.RedirectStandardOutput = true;
  8.     processStartInfo.UseShellExecute = false;
  9.     process = Process.Start(processStartInfo);
  10.  
  11.     /* Start a background task that copies the spawned process
  12.      * standard output stream to our own standard output stream */
  13.     Task.Factory.StartNew(() =>
  14.     {
  15.         process.StandardOutput.BaseStream.CopyTo(Console.OpenStandardOutput());
  16.     });
  17.  
  18.     process.WaitForExit();
  19.     return process.ExitCode;
  20. }