gpt4 book ai didi

c# - process.standardoutput.ReadToEnd() 总是空的?

转载 作者:可可西里 更新时间:2023-11-01 08:16:53 31 4
gpt4 key购买 nike

我正在启动一个控制台应用程序,但是当我重定向标准输出时,我总是什么也得不到!

当我不重定向它,并将 CreateNoWindow 设置为 false 时,我在控制台中正确地看到了所有内容,但是当我重定向它时,StandardOutput。 ReadToEnd() 始终返回一个空字符串。

        Process cproc = new Process();
cproc.StartInfo.CreateNoWindow = true;
cproc.StartInfo.FileName = Dest;
cproc.StartInfo.RedirectStandardOutput = true;
cproc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cproc.StartInfo.UseShellExecute = false;
cproc.EnableRaisingEvents = true;
cproc.Start();
cproc.Exited += new EventHandler(cproc_Exited);
while(!stop)
{
result += cproc.StandardOutput.ReadToEnd();
}

EventHandler cproc_exited 只是将stop 设置为true。有人可以解释为什么 result 总是 string.Empty 吗?

最佳答案

最好的方法是重定向输出并等待事件:

    // not sure if all this flags are needed
process.StartInfo.CreateNoWindow = true;
process.StartInfo.ErrorDialog = false;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.EnableRaisingEvents = true;
process.OutputDataReceived += process_OutputDataReceived;
process.ErrorDataReceived += process_ErrorDataReceived;
process.Exited += process_Exited;
process.Start();

void process_Exited(object sender, System.EventArgs e)
{
// do something when process terminates;
}

void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
// a line is writen to the out stream. you can use it like:
string s = e.Data;
}

void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
// a line is writen to the out stream. you can use it like:
string s = e.Data;
}

关于c# - process.standardoutput.ReadToEnd() 总是空的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2012509/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com