问题
Trying to process a diff command gives me an error:
diff: extra operand `>'
Error is the same regardless of platform (under windows, I'm using 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()
回答1:
This happens because > is not a part of the command arguments but the standard output redirection operand which is handled not by the process itself, but by the OS starting the process.
When starting a process through code, we need to handle this by ourselves.
Here is a solution working on 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();
EDIT 1:
Having these two files (old.txt and 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
The output (diff.txt) is as follows:
Line 1 - def
Line 1 - def
Line 1 - def
Line 1 - def
来源:https://stackoverflow.com/questions/61296870/system-diagnostics-process-start-arguments-dotnet-and-diff