gpt4 book ai didi

c# - ProcessInfo 和 RedirectStandardOutput

转载 作者:IT王子 更新时间:2023-10-29 04:15:12 24 4
gpt4 key购买 nike

我有一个应用程序在命令窗口中调用另一个进程,并且该进程更新了输出到控制台窗口的统计信息。我认为这是一个相当简单的操作,但我似乎无法让它工作。我错过了什么吗?

string assemblyLocation = Assembly.GetExecutingAssembly().Location;

Process process = new Process
{
ProcessStart =
{
RedirectStandardOutput = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
Arguments = arg,
FileName = assemblyLocation.Substring(0, assemblyLocation.LastIndexOf("\\")) + "\\ffmpeg.exe",
CreateNoWindow = true
}
};

process.Start();

Console.WriteLine(process.StandardOutput.ReadToEnd());

process.WaitForExit();

理想情况下,我想要的是当我点击的那个过程中的输出发生变化或者数据进入读取器时我从中获取事件。

任何帮助都会很棒,我觉得这是一个新手问题,但似乎遗漏了一些东西。

最佳答案

我以前有过这种经历。有时,您调用输出到控制台的过程与这种输出重定向不兼容。在这种情况下,我很幸运能够修改外部流程来解决这个问题。

您可以尝试在输出到控制台的另一个进程上运行您的代码,看看它是否正常工作。它现在对我来说是正确的。

编辑:

我去拉了一个我用来做这个的代码块。这是在将进程输出重定向到窗口的 WPF 应用程序中。注意事件绑定(bind)。因为这是 WPF,所以我必须调用我的调用来写出数据。由于您不担心阻塞,您应该能够简单地将其替换为:

Console.WriteLine(e.Data);

希望对您有所帮助!

    private static void LaunchProcess()
{
Process build = new Process();
build.StartInfo.WorkingDirectory = @"dir";
build.StartInfo.Arguments = "";
build.StartInfo.FileName = "my.exe";

build.StartInfo.UseShellExecute = false;
build.StartInfo.RedirectStandardOutput = true;
build.StartInfo.RedirectStandardError = true;
build.StartInfo.CreateNoWindow = true;
build.ErrorDataReceived += build_ErrorDataReceived;
build.OutputDataReceived += build_ErrorDataReceived;
build.EnableRaisingEvents = true;
build.Start();
build.BeginOutputReadLine();
build.BeginErrorReadLine();
build.WaitForExit();
}

// write out info to the display window
static void build_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
string strMessage = e.Data;
if (richTextBox != null && !String.Empty(strMessage))
{
App.Instance.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate()
{
Paragraph para = new Paragraph(new Run(strMessage));
para.Margin = new Thickness(0);
para.Background = brushErrorBrush;
box.Document.Blocks.Add(para);
});
}
}

关于c# - ProcessInfo 和 RedirectStandardOutput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1145969/

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