0

I tried to get the output of passed argument in the cmd.exe via c# code. But when the code string outw = cmd.StandardOutput.ReadToEnd().ToString(); executing takes more and more time. Here my command prompt arguments work perfectly.

Here is my code

        Process cmd = new Process();
        cmd.StartInfo.FileName = "cmd.exe";
        cmd.StartInfo.RedirectStandardInput = true;
        cmd.StartInfo.RedirectStandardOutput = true;
        cmd.StartInfo.CreateNoWindow = true;
        cmd.StartInfo.UseShellExecute = false;
        cmd.Start();
        cmd.StandardInput.WriteLine("git init && git remote add gitlab https://gitlab.company.com/test2.git && git push gitlab --delete branchname");
        cmd.StandardInput.WriteLine("git remote remove gitlab");
        string outw = cmd.StandardOutput.ReadToEnd().ToString();//Here my code strucks
        cmd.StandardInput.Flush();
        cmd.StandardInput.Close();
        cmd.WaitForExit();

Where I made the mistake? I waited for more than 30 min but I did not get the output in the string outw. How could I get the output test as a string in string outw?

  • 1
    Possible duplicate of [Process.start: how to get the output?](https://stackoverflow.com/questions/4291912/process-start-how-to-get-the-output) – Pranav Patel May 29 '17 at 09:05
  • 6
    Trying to work with `cmd.exe` interactively feels like it could easily be a lot harder than just launching each process directly... – Jon Skeet May 29 '17 at 09:05
  • What Jon says is true, unless you need some of the special features of the Command Prompt shell. That isn't true in this case; in fact, with git, the Windows-isms of cmd.exe are likely to be more annoying than helpful. – Cody Gray - on strike May 29 '17 at 09:09
  • 5
    You forgot to tell cmd.exe to quit running. So ReadToEnd() never completes. There are better ways to do this, but sending "exit" should be the simple solution. – Hans Passant May 29 '17 at 09:09
  • I suspect the answer would be pretty easy to see if you didn't use `CreateNoWindow`. In particular, I suspect that cmd doesn't exit, given that you didn't tell it to. Also note that some git commands don't use the standard I/O streams, so don't be too surprised if you get garbage out of some of them (the ones in your code should be fine IIRC), – Luaan May 29 '17 at 09:10
  • https://stackoverflow.com/questions/7160187/standardoutput-readtoend-hangs – CodeCaster May 29 '17 at 09:13
  • Also, just use LibGit2Sharp. – CodeCaster May 29 '17 at 09:13
  • @HansPassant How can I send the "exit" ? –  May 29 '17 at 11:43
  • The exact same why you sent "git". – Hans Passant May 29 '17 at 11:49

0 Answers0