-1

Im trying to get the outpout of my CMD command and i get the wrong outpout:

here's my cmd command : cm whoami

here's the outpout i should get (CMD outpout) :

C:\Users\Joevin>cm whoami
JoevinFerret

here's my code :

 Process process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = "cm whoami",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    CreateNoWindow = true
                }
            };
            process.Start();
            string outpout = process.StandardOutput.ReadLine();

here's the outpout that i get : outpout = "Microsoft Windows [Version 10.0.19041.804]"

  • 2
    Try `ReadToEnd()` instead of `ReadLine()` – Mathias R. Jessen Feb 15 '21 at 16:27
  • 2
    There are a number of things wrong with your example (hints: `cmd.exe /c ...`, `ReadLine()` only captures first line of multi-line output, attempt to run your command manually and see what output it produces). If you search SO ("[c#] cmd output") you'll find a multitude of related (or exact same) questions and answers. Just [one example](https://stackoverflow.com/questions/43112187/c-sharp-get-cmd-output-just-as-shown-in-real-cmd-window). – Christian.K Feb 15 '21 at 16:29
  • Ok thanks i have change my ReadLine() to ReadToEnd() add a WaitForExit() to my process and add "/c" at the begining of my arguments and it's work –  Feb 15 '21 at 16:36

1 Answers1

1

Thanks to Mathias.R and Christian.K i have been able to find a solution.

Here's my code:

 Process process = new Process
 {
     StartInfo = new ProcessStartInfo
     {
         FileName = "cmd.exe",
         Arguments = "/c cm whoami",
         UseShellExecute = false,
         RedirectStandardOutput = true,
         CreateNoWindow = true
     }
 };
 process.Start();
 string outpout = process.StandardOutput.ReadToEnd();
 process.WaitForExit();