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

北城余情 提交于 2021-01-28 08:31:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!