如果通过Process
类运行,您可以重定向流,以便您可以处理它们.您可以同步或异步读取stdout或stderr.要启用重定向,请为要重定向true
的流(例如,RedirectStandardOutput
)设置相应的重定向属性,并将其设置UseShellExecute
为false
.然后你就可以开始这个过程并从流中读取.您还可以输入重定向标准输入的输入.
例如,处理并打印进程同步写入stdout的任何内容
var proc = new Process()
{
StartInfo = new ProcessStartInfo(@"SomeProcess.exe")
{
RedirectStandardOutput = true,
UseShellExecute = false,
}
};
if (!proc.Start())
{
// handle error
}
var stdout = proc.StandardOutput;
string line;
while ((line = stdout.ReadLine()) != null)
{
// process and print
Process(line);
Console.WriteLine(line);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这里有一个MSDN示例 ...这是一个简化的版本:
var StdOut = "";
var StdErr = "";
var stdout = new StringBuilder();
var stderr = new StringBuilder();
var psi = new ProcessStartInfo();
psi.FileName = @"something.exe";
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
var proc = new Process();
proc.StartInfo = psi;
proc.OutputDataReceived += (sender, e) => { stdout.AppendLine(e.Data); };
proc.ErrorDataReceived += (sender, e) => { stderr.AppendLine(e.Data); };
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit(10000); // per sachin-joseph's comment
StdOut = stdout.ToString();
StdErr = stderr.ToString();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7284 次 |
最近记录: |