我正在尝试使用System.Diagnostics.Process
派生Git实例并将其输出重定向到我自己的程序中。我正在使用以下最少的代码:
using (var process = new Process
{
StartInfo = {
FileName = @"C:\Program Files\Git\bin\git.exe",
UseShellExecute = false,
RedirectStandardError = true,
Arguments = $"clone --progress --bare {RepositoryUrl} {destinationDirectory}"
}
})
{
process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
process.Start();
process.BeginErrorReadLine();
process.WaitForExit();
}
运行此代码将产生以下输出:
Cloning into bare repository '<redacted>'...
remote: Enumerating objects: 5, done.
remote: Counting objects: 20% (1/5)
remote: Counting objects: 40% (2/5)
<snip>
remote: Counting objects: 100% (5/5)
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 33% (1/3)
remote: Compressing objects: 66% (2/3)
remote: Compressing objects: 100% (3/3)
remote: Compressing objects: 100% (3/3), done.
Receiving objects: 0% (1/4973)
Receiving objects: 1% (50/4973)
<snip>
Receiving objects: 46% (2288/4973)
Receiving objects: 47% (2338/4973)
Receiving objects: 48% (2388/4973), 6.95 MiB | 13.89 MiB/s
Receiving objects: 49% (2437/4973), 6.95 MiB | 13.89 MiB/s
<snip>
Receiving objects: 98% (4874/4973), 18.66 MiB | 18.66 MiB/s
Receiving objects: 99% (4924/4973), 18.66 MiB | 18.66 MiB/s
remote: Total 4973 (delta 0), reused 5 (delta 0)
Receiving objects: 100% (4973/4973), 18.66 MiB | 18.66 MiB/s
Receiving objects: 100% (4973/4973), 21.21 MiB | 17.53 MiB/s, done.
Resolving deltas: 0% (0/1261)
Resolving deltas: 1% (14/1261)
<snip>
Resolving deltas: 100% (1261/1261)
Resolving deltas: 100% (1261/1261), done.
在终端中,重复的行实际上彼此覆盖,因此显示一个递增计数器。这是通过输出回车来完成的,回车将终端的光标重置为第一列。
另一方面,似乎Process
基础结构会剥离所有换行符(按预期方式)以及回车符,然后再将Git的输出返回给我的代码。我不能只是将它们放回自己,因为不是所有Git的输出都应该使用它们,而且一旦剥离它们,我也无法告诉哪些输出。
如何在Process
的异步输出重定向中禁用特殊字符剥离以按原样接收输出?