Home | Software | WebLog | Contact | Wish List

Joel Thoms' WebLog

Here you will find random thoughts, opinions and rants from Joel Thoms. Feel free to ignore it all...
Mon, 26 Mar 2007

There are many code samples that show you how to read from either StandardOutput or StandardError.  I've also run across a few more complicated code examples that spawn new processes to handle the reading of StandardOutput and StandardError.

Reading from StandardOut (or StandardError) is simple, all you need to do is set a property and create a simple loop...

proc.StartInfo.RedirectStandardOutput = true;

while (!proc.StandardOutput.EndOfStream) {
  string line = proc.StandardOutput.ReadLine();
  Console.WriteLine(">{0}", line);
}

Reading both is not much more complex.  You just have to test EndOfStream on both streams.
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.FileName = Environment.CurrentDirectory + @"\" + zipCmd;
proc.StartInfo.Arguments = String.Format("-rSv \"{0}\" .", zipFile);
proc.StartInfo.WorkingDirectory = directory;
proc.Start();

while (!proc.StandardOutput.EndOfStream || !proc.StandardError.EndOfStream) {
  string line;

  if (!proc.StandardOutput.EndOfStream
    && (line = proc.StandardOutput.ReadLine()) != null) {
    Console.WriteLine(">>{0}", line);
  }
  if (!proc.StandardError.EndOfStream
    && (line = proc.StandardError.ReadLine()) != null) {
    Console.WriteLine("!!{0}", line);
  }
}
Pages: << back<< back

WebLogs powered by Joel.Net.WebLogs