1

I trying to run the following command in cmd.exe by c# code.

  1. mkdir myfolder
  2. cd myfolder
  3. git init
  4. git remote set-url origin https://gitlab.company.com/testgroup/server.git
  5. git fetch --dry-run
  6. cd ..
  7. rmdir myfolder

I don't know how to pass all the arguments in single Process.Start();. After run the 4th command I will take the output string and do some operation with that string.

I tried like this

        const string strCmdText = "/C mkdir myfolder& cd myfolder& git init & git remote set-url origin https://gitlab.company.com/project.git & git fetch --dry-run & cd .. & rmdir myfolder";
        Process.Start("CMD.exe", strCmdText);

Above command works properly. But I do not know how to get the execution text from cmd.exe. The text which I want is shown in below image.

The text I want

I used below code to get the output string. But at the line of reading the output(string output = cmd.StandardOutput.ReadToEnd();), the execution stopped. I means it will not go to next line also it will not terminate the program. Simply show the lack screen.

        Process cmd = new Process();
        cmd.StartInfo.FileName = "cmd.exe";
        cmd.StartInfo.Arguments = "/C mkdir myfolder& cd myfolder& git init & git remote set-url origin https://gitlab.company.com/project.git & git fetch --dry-run & cd .. & rmdir myfolder";
        cmd.StartInfo.UseShellExecute = false;
        cmd.StartInfo.RedirectStandardOutput = true;
        cmd.StartInfo.RedirectStandardError = true;
        cmd.Start();
        string output = cmd.StandardOutput.ReadToEnd();
        Console.WriteLine(output);

How do I get the output string?

1 Answers1

0

If you use 'ReadToEnd', you will wait for end of stream. You should use 'Read' or 'ReadLine' for reading parts of available stream context:

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = "/C mkdir myfolder& cd myfolder& git init & git remote set-url origin https://gitlab.company.com/project.git & git fetch --dry-run & cd .. & rmdir myfolder";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.Start();

while (!cmd.StandardOutput.EndOfStream) {
    string line = cmd.StandardOutput.ReadLine();
    Console.WriteLine(line);
}
Ivan Kishchenko
  • 795
  • 4
  • 15
  • I altered my code as you said but I facing the same black screen exception in `while (!cmd.StandardOutput.EndOfStream)` line –  Mar 13 '17 at 10:29
  • Very strange, because for me it works fine. Try this on clear C# console project. – Ivan Kishchenko Mar 13 '17 at 11:41