Saturday, 7 April 2012

C#: Read from command Prompt

I've been trying to read from Command prompt using c#. My application supposed to read lines from cmd whatever it shows. My Purpose was developing code editor and using external compiler.
 You need to use  System.Diagnostics.Process(System.Diagnostics.ProcessStartInfo).

System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo("file.exe", "command");
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
startInfo.StandardOutputEncoding = //change if you need, you might need it
startInfo.StandardErrorEncoding = //change if you need, you might need it
//...

Using this example, file.exe could be any executable file and command, it should be related to exe file. In this example, file.exe is "cmd.exe" and "command" is "RUNCOB"

 Use instance method of System.Diagnostics.Process.Start as shown below:
 Process process1 = new Process(); // Creates instance method.
process1.StartInfo.UseShellExecute = false; // in order to use output stream.
process1.StartInfo.RedirectStandardOutput = true; // enables to get output stream
process1.StartInfo.FileName = "cmd.exe";
process1.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// process1.WaitForExit();
// Read the output stream first and then wait.
string output = process1.StandardOutput.ReadToEnd();
process1.WaitForExit();

You will find detailed explanation here:
process.standardOutput[^
Make sure you setup output streams as shown in the code sample (see the reference above). Read the streams to the end using Process.StandardOutput.ReadToEnd and Process.StandardError.ReadToEnd. (You use instance of the Process here.)
Make sure you use System.Diagnostics.Process.Start

You can parse the compiler output string into line like this.

string streamOutput = myProcess.StandardOutput.ReadToEnd();

string[] lines = streamOutput.Split(new string[] { System.Environment.NewLine, }, 
System.StringSplitOptions.None);
//for goodness sake:
//don't use \r\n or something: this is not portable
it's best to dedicate a separate thread for that. You can keep the thread running, sitting at wait state using the blocked call System.Threading.EventWaitHandle.WaitOne and unblock it every time the file(s) is commanded for compilation calling System.Threading.EventWaitHandle.Set from your main thread (you UI thread if you use UI).

As this is not UI thread, you cannot use UI from this thread, not directly. You can only use invocation via System.Windows.Forms.Control or System.Threading.Dispatchervia their methods Invoke or BeginInvoke.

You will find detailed explanation here:
Control.Invoke() vs. Control.BeginInvoke()[^],
see also:
Problem with Treeview Scanner And MD5[^].



BySergey A. Kryukov

Here is complete source code of using external compiler.
Maybe you will need to check errors.
private void executeToolStripMenuItem_Click(object sender, EventArgs e)
{
try
   {
      Process process = new System.Diagnostics.Process();
      stratInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", 
"/c RUNCOB hello.cob");
      stratInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
         // i wanted to use compiler as a background processor.
      stratInfo.UseShellExecute = false;
      stratInfo.RedirectStandardError = true; 
// just in case, if there is any error.
      stratInfo.RedirectStandardOutput = true;
      stratInfo.WorkingDirectory = dir_path; 
// directory which includes my compiler
        // in this case "cobol" compiler
      process.StartInfo = stratInfo;
      process.Start();
     string streamOutput = process.StandardOutput.ReadToEnd();
     string[] ls = streamOutput.Split(new string[] 
{ System.Environment.NewLine, },                     
System.StringSplitOptions.None);
     richTextBox1.Text = "";
     foreach (string tmp in ls)
         this.richTextBox1.AppendText(tmp);
     this.lbl_compile_status.Text = "Run";
  }
   catch (IOException ioe)
   { Console.WriteLine(ioe.Message); }
}

No comments:

Post a Comment