How to redirect console output – csharp .net ?

Question: How to redirect console output – csharp .net ?

Answer:

 //Create Process Start information
 40                      ProcessStartInfo processStartInfo =
 41                          new ProcessStartInfo(txtExecutable.Text.Trim(), txtParameter.Text.Trim());
 42                      processStartInfo.ErrorDialog = false;
 43                      processStartInfo.UseShellExecute = false;
 44                      processStartInfo.RedirectStandardError = true;
 45                      processStartInfo.RedirectStandardInput = true;
 46                      processStartInfo.RedirectStandardOutput = true;
 47  
 48                      //Execute the process
 49                      Process process = new Process();
 50                      process.StartInfo = processStartInfo;
 51                      bool processStarted = process.Start();
 52                      if (processStarted)
 53                      {
 54                          //Get the output stream
 55                          outputReader = process.StandardOutput;
 56                          errorReader = process.StandardError;
 57                          process.WaitForExit();
 58  
 59                          //Display the result
 60                          string displayText = "Output" + Environment.NewLine + "==============" + Environment.NewLine;
 61                          displayText += outputReader.ReadToEnd();
 62                          displayText += Environment.NewLine + "Error" + Environment.NewLine + "==============" +
 63                                         Environment.NewLine;
 64                          displayText += errorReader.ReadToEnd();
 65                          txtResult.Text = displayText;
 66                      }
 67                  }
 68                  catch (Exception ex)
 69                  {
 70                      MessageBox.Show(ex.Message);
 71                  }
 72                  finally
 73                  {
 74                      if(outputReader != null)
 75                      {
 76                          outputReader.Close();
 77                      }
 78                      if(errorReader != null)
 79                      {
 80                          errorReader.Close();
 81                      }
 82                      btnStart.Enabled = true;
 83                  }
 84              }
Advertisements

About Firat Karakusoglu

IIT Tech.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: