System.Diagnostics.Process.Start() 参数 dotnet 和 diff

System.Diagnostics.Process.Start() arguments dotnet and diff

尝试处理 diff 命令时出现错误:

diff: extra operand `>'

无论平台如何,错误都是一样的(在 windows 下,我使用的是 choco diffutils)。

var cmd = "diff" //if ran under windows is the choco path: C:\ProgramData\chocolatey\bin\diff.exe
var args = "--unchanged-group-format='' --old-group-format='' --changed-group-format='%>' --new-group-format='' old.txt new.txt > diff.txt"
var p = System.Diagnostics.Process.Start(cmd, args)
p.WaitForExit()

发生这种情况是因为 > 不是命令参数的一部分,而是标准输出重定向操作数,它不是由进程本身处理的,而是由 OS 启动进程处理的。

通过代码启动进程时,需要我们自己处理。

这是一个针对 windows 的解决方案:

var cmd = "diff"; //if ran under windows is the choco path: C:\ProgramData\chocolatey\bin\diff.exe
var args = "--unchanged-group-format=\"\" --old-group-format=\"\" --changed-group-format=\"%>\" --new-group-format=\"\" old.txt new.txt";

var p = new Process();

p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = cmd;
p.StartInfo.Arguments = args;
p.StartInfo.RedirectStandardOutput = true;

p.Start();

using (var outputFile = File.OpenWrite("diff.txt"))
{
    p.StandardOutput.BaseStream.CopyTo(outputFile);
}

p.WaitForExit();

编辑 1:

有这两个文件(old.txt 和 new.txt)

   old.txt             new.txt
Line 1 - abc        Line 1 - def
Line 2 - def        Line 2 - def
Line 1 - abc        Line 1 - def
Line 2 - def        Line 2 - def

输出(diff.txt)如下:

Line 1 - def
Line 1 - def
Line 1 - def
Line 1 - def