-1

我想使用 C# 启动一个 .exe 程序并从 .exe 生成的 cmd 读取值

.exe 成功启动,但我无法读取值:

这是我的代码:

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;
    }
}
4

3 回答 3

1

你需要这样的东西:

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

其中 p 是Process p = new Process();

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

其中 data 是一个 int 列表

于 2013-05-16T09:06:45.317 回答
1

正如 Sam I Am 所指出的,删除 using 块StreamReader

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

但是请记住,您的调用应用程序将阻塞,直到过程完成并且可以读取所有输出。

于 2013-05-08T18:23:14.777 回答
0

我在您的代码中没有看到任何奇怪的东西,它应该可以正常工作。看一下文档,它给出了一个如何重定向它的简短示例:

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

来源:Process.StandardOutput 属性

于 2013-05-08T18:33:55.760 回答