The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Jul 2008»»
SMTWTFS
  
1
2
3
4
5
6789101112
13141516171819
20212223242526
2728293031

My RSS Feeds








Mailing List

Most Popular Tags

                                       

How to send the Console output to a string

posted Friday, 19 May 2006

Sometimes when writing a tool or automated process, you want to read in the console output and send it to a string. From there, you can do whatever you want to it, such as parse for info. For example, a third-party tool (not necessarily even built with .Net) may display result information to the console, and you may want that info as part of some bigger process. The classes to do this reside in System.Diagnostics.


    public static string GetConsoleOutput(string strFileName, string strArguments)
    {

      ProcessStartInfo psi = new ProcessStartInfo();
      StringBuilder sb = new StringBuilder();
      try
      {
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        //Need to include this for Executable version (appears not to be needed if UseShellExecute=true)
        psi.CreateNoWindow = true;   
        psi.FileName = strFileName;
        psi.Arguments = strArguments;
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;

        Process p = Process.Start(psi);

        sb.Append(p.StandardOutput.ReadToEnd());
        sb.Append(p.StandardError.ReadToEnd());

        p.WaitForExit();

      }
      catch (Exception ex)
      {
        sb.Append("\r\nPROCESS_ERROR:" + ex.ToString()); ;
      }
      return sb.ToString();

    }

tags:    

links: digg this    technorati    




1. Mike left...
Saturday, 30 September 2006 11:36 pm

Is this correct? What if the child process writes enough output to StdErr, thus blocking waiting for the parent process to flush it? But the parent process is blocked waiting to read from StandardOut.

In other words, your code snippet above will hang when run on this program:

using System;

class Foo { static void Main() { Console.WriteLine("Hi!"); Console.Error.WriteLine("error"); // fill the std error buffer string x = new String('a', 10000); Console.Error.WriteLine(x);

string y = new String('b', 10000); Console.Out.WriteLine(y);

Console.WriteLine("Exit"); } }