How To: Execute command line in C#, get STD OUT results

后端 未结 17 1293
既然无缘
既然无缘 2020-11-21 13:12

How do I execute a command-line program from C# and get back the STD OUT results? Specifically, I want to execute DIFF on two files that are programmatically selected and wr

17条回答
  •  我寻月下人不归
    2020-11-21 14:08

    The accepted answer on this page has a weakness that is troublesome in rare situations. There are two file handles which programs write to by convention, stdout, and stderr. If you just read a single file handle such as the answer from Ray, and the program you are starting writes enough output to stderr, it will fill up the output stderr buffer and block. Then your two processes are deadlocked. The buffer size may be 4K. This is extremely rare on short-lived programs, but if you have a long running program which repeatedly outputs to stderr, it will happen eventually. This is tricky to debug and track down.

    There are a couple good ways to deal with this.

    1. One way is to execute cmd.exe instead of your program and use the /c argument to cmd.exe to invoke your program along with the "2>&1" argument to cmd.exe to tell it to merge stdout and stderr.

              var p = new Process();
              p.StartInfo.FileName = "cmd.exe";
              p.StartInfo.Arguments = "/c mycmd.exe 2>&1";
      
    2. Another way is to use a programming model which reads both handles at the same time.

              var p = new Process();
              p.StartInfo.FileName = "cmd.exe";
              p.StartInfo.Arguments = @"/c dir \windows";
              p.StartInfo.CreateNoWindow = true;
              p.StartInfo.RedirectStandardError = true;
              p.StartInfo.RedirectStandardOutput = true;
              p.StartInfo.RedirectStandardInput = false;
              p.OutputDataReceived += (a, b) => Console.WriteLine(b.Data);
              p.ErrorDataReceived += (a, b) => Console.WriteLine(b.Data);
              p.Start();
              p.BeginErrorReadLine();
              p.BeginOutputReadLine();
              p.WaitForExit();
      

提交回复
热议问题