Showing posts with label console. Show all posts
Showing posts with label console. Show all posts

Thursday, May 18, 2006

How to send the Console output to a string

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/how_to_send_the_console_output_to_a_string.htm]

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();

    }