-1

I want to launch a .exe program using C# and read the values from the cmd generated from the .exe

The .exe launches successfully but I cannot read the values:

This is my code:

ProcessStartInfo start = new ProcessStartInfo();

start.FileName = (@"D:\BSC\Thesis\Raphael_Thesis\smiledetector\bin\smiledetector.exe");
start.WorkingDirectory = @"D:\BSC\Thesis\Raphael_Thesis\smiledetector\bin\";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;

//Start the process

using (Process process = Process.Start(start))
{
    // Read in all the text from the process with the StreamReader.
    using (StreamReader reader = process.StandardOutput)
    {
        string result = reader.ReadToEnd();
        textBox1.Text = result;
    }
}
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90

3 Answers3

1

As Sam I Am has indicated, drop the using block for the StreamReader

using (Process process = Process.Start(start))
{ 
    string result = process.StandardOutput.ReadToEnd();
    textBox1.Text = result;
}

Keep in mind however your calling application will block until process completes and all the output can be read.

Lee Hiles
  • 1,125
  • 7
  • 9
1

You need something like this:

private void btnStart_Click(object sender, EventArgs e)
{
    p.StartInfo.FileName = @"D:\BSC\Thesis\Raphael_Thesis\smileDetector\vs2010\smiledetectorDebug";
    p.StartInfo.WorkingDirectory = @"D:\BSC\Thesis\Raphael_Thesis\smileDetector\vs2010\";
    p.StartInfo.RedirectStandardOutput = true;
    p.EnableRaisingEvents = true;
    p.StartInfo.UseShellExecute = false;

    p.OutputDataReceived += new DataReceivedEventHandler(OutputHander);

    p.Start();
    p.BeginOutputReadLine();
    p.WaitForExit();
}

where p is Process p = new Process();

void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    data.Add(Convert.ToInt32(e.Data));
}

where data is a List of int

Stefan
  • 17,448
  • 11
  • 60
  • 79
0

I don't see any weird thing in your code, it should work fine. Taking a look at the doc, it gives a brief example of how to redirect it:

 // Start the child process.
 using(Process p = new Process())
 {
   // Redirect the output stream of the child process.
   p.StartInfo.UseShellExecute = false;
   p.StartInfo.RedirectStandardOutput = true;
   p.StartInfo.FileName = @"D:\BSC\Thesis\Raphael_Thesis\smiledetector\bin\smiledetector.exe";
   p.WorkingDirectory = @"D:\BSC\Thesis\Raphael_Thesis\smiledetector\bin\";
   p.Start();
   // Do not wait for the child process to exit before
   // reading to the end of its redirected stream.
   // p.WaitForExit();
   // Read the output stream first and then wait.
   string output = p.StandardOutput.ReadToEnd();
   p.WaitForExit();
 }

source: Process.StandardOutput Property

GoRoS
  • 5,183
  • 2
  • 43
  • 66