读取过程输出时发生异常

时间:2018-10-29 22:49:12

标签: c++ command-line process c++-cli clr

我的问题如下:

我有一个在Visual Studio中使用C ++ / CLI创建的UI。 现在,我有一个按钮事件,该事件创建一个运行带有参数的C ++控制台应用程序的过程。

这很好用,控制台应用程序将使用没有错误的参数执行,而且我还会看到具有正确输出的控制台窗口。

但我仍然得到一个例外:

  

StandardOut尚未重定向或该过程尚未开始。

我认为这与Streamreader和一些DataReceivedEvents有关,但我没有头绪。

这是我的代码:

try {

        String^ parameters = tbLoadXML->Text + " " + tbNumberAnts->Text + " " + tbIteration->Text + " " + tbReduction->Text + " " + tbPheromoneDeposit->Text + " " + tbPheromoneReduction->Text + " " + tbAlpha->Text + " " + tbBeta->Text + " " + reduce.ToString() + " " + algorithm.ToString() + " " + probabilityalgorithm.ToString() + " " + numbercities.ToString();

        Process^ process = gcnew Process();
        process->StartInfo->UseShellExecute = false;
        process->StartInfo->CreateNoWindow = true;      
        process->StartInfo->RedirectStandardOutput = true;
        process->Start("TSPACO.exe", parameters);

        StreamReader^ reader = process->StandardOutput;
        String^ output = reader->ReadToEnd();       

        textBox1->Text += output;

        process->WaitForExit();
        process->Close();
    }
    catch (Exception^ ex) {
        MessageBox::Show(ex->Message);
    }   

我也尝试了while循环:

while (!process->StandardOutput->EndOfStream)
{
            textBox1->Text += process->StandardOutput->ReadLine();
}

但是什么都没用-我不知道为什么。

1 个答案:

答案 0 :(得分:0)

所以我想出了一个解决问题的办法-我不知道为什么会这样,但是我认为诀窍是创建一个具有所有必需属性的ProcessStartInfo-Object,然后只使用默认的Process :: Start方法,而无需任何参数:

    ProcessStartInfo^ startInfo = gcnew ProcessStartInfo();
    startInfo->FileName = "TSPACO.exe";
    startInfo->Arguments = parameters;
    startInfo->UseShellExecute = false;
    startInfo->CreateNoWindow = true;
    startInfo->RedirectStandardOutput = true;

    Process^ process = gcnew Process();
    process->StartInfo = startInfo;
    process->Start();

    StreamReader^ reader = process->StandardOutput;
    String^ output = reader->ReadToEnd();

    textBox1->Text += output;

    process->WaitForExit();
    process->Close();
相关问题