C# 从命令行重新解析响应
Im使用命令行应用程序对视频进行编码。该应用程序返回一行,其中显示: %完成率:34% 这会随着媒体编码而更新。是否有一种方法可以使用process类不断检查标准输出并将其传递回主执行脚本?我有一个类,它启动流程,然后将标准输出写入stringbuilder,但我想知道如何继续检查它。这是当前代码C# 从命令行重新解析响应,c#,process,console-application,C#,Process,Console Application,Im使用命令行应用程序对视频进行编码。该应用程序返回一行,其中显示: %完成率:34% 这会随着媒体编码而更新。是否有一种方法可以使用process类不断检查标准输出并将其传递回主执行脚本?我有一个类,它启动流程,然后将标准输出写入stringbuilder,但我想知道如何继续检查它。这是当前代码 public static Dictionary<string, string> StartProcess(string exePathArg, string argumentsArg,
public static Dictionary<string, string> StartProcess(string exePathArg, string argumentsArg, int timeToWaitForProcessToExit)
{
//the dictionary with the
Dictionary<string, string> retDirects = new Dictionary<string, string>();
using (Process p = new Process())
{
p.StartInfo.FileName = exePathArg;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.Arguments = argumentsArg;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
try
{
p.Start();
p.WaitForExit(timeToWaitForProcessToExit);
int exitCode;
try
{
exitCode = p.ExitCode;
StreamReader standardOutput = p.StandardOutput;
StreamReader standardError = p.StandardError;
retDirects.Add("StandardOutput", standardOutput.ReadToEnd());
retDirects.Add("StandardError", standardError.ReadToEnd());
}
catch { }
}
catch { }
finally
{
try
{
p.Kill();
p.CloseMainWindow();
}
catch { }
}
}
return retDirects;
}
publicstaticdictionary启动进程(字符串exepath arg、字符串argumentsArg、int-timeToWaitForProcessToExit)
{
//这本字典有
Dictionary=newdictionary();
使用(进程p=新进程())
{
p、 StartInfo.FileName=exePathArg;
p、 StartInfo.RedirectStandardOutput=true;
p、 StartInfo.RedirectStandardError=true;
p、 StartInfo.Arguments=argumentsArg;
p、 StartInfo.UseShellExecute=false;
p、 StartInfo.CreateNoWindow=true;
尝试
{
p、 Start();
p、 WaitForExit(timeToWaitForProcessToExit);
int exitCode;
尝试
{
exitCode=p.exitCode;
StreamReader standardOutput=p.standardOutput;
StreamReader standardError=p.standardError;
添加(“StandardOutput”,StandardOutput.ReadToEnd());
添加(“StandardError”,StandardError.ReadToEnd());
}
捕获{}
}
捕获{}
最后
{
尝试
{
p、 杀死();
p、 关闭主窗口();
}
捕获{}
}
}
返回指令;
}
您可以使用进程.BeginOutputReadLine
启动进程.outputDataReceived
事件UseShellExecute
必须为false
且RedirectOutput
必须为true,如示例代码中所示
这里有一个例子,我不会重复。我注意到,有些程序使用不同的流来实现我认为是意外的目的,因此可能适合对不同流中的事件使用相同的处理程序。您可以使用
进程。BeginOutputReadLine
启动进程。OutputDataReceived
事件UseShellExecute
必须为false
且RedirectOutput
必须为true,如示例代码中所示
这里有一个例子,我不会重复。我注意到,有些程序使用不同的流来达到我认为不可预期的目的,因此对来自不同流的事件使用相同的处理程序可能是合适的。在循环中使用几个字节(甚至一次一个字节)的“Read”,而不是使用“ReadToEnd”。Read将阻塞,直到它读取指定的字节数为止。找到正确的字节数,您应该能够从标准输出中读取字符串。在循环中使用几个字节(甚至每次一个字节)的“读取”,而不是使用“ReadToEnd”。Read将阻塞,直到它读取指定的字节数为止。找到正确的字节数,您应该能够从标准输出中读取字符串。我记得,您可以将一个委托作为StartInfo的一部分传入,当新数据到达时,该委托将被“回调”。我记得,您可以将一个委托作为StartInfo的一部分传入,当新数据到达时,该委托将被“回调”。