8

I want to run commands on the cmd from my C# app.

I tried:

string strCmdText = "ipconfig";
        System.Diagnostics.Process.Start("CMD.exe", strCmdText);  

result:

the cmd window pop but the command didn't do nothing.

why?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user2257505
  • 91
  • 1
  • 1
  • 3

2 Answers2

11

Use

System.Diagnostics.Process.Start("CMD.exe", "/C ipconfig");  

If you want to have cmd still opened use:

System.Diagnostics.Process.Start("CMD.exe", "/K ipconfig");  
chaliasos
  • 9,659
  • 7
  • 50
  • 87
Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
  • and then how to send future commands? – Hamed Zakery Miab Oct 04 '17 at 11:54
  • 2
    It is very common for people to prepend a command invocation with `cmd /c` even though it's not always necessary. In this case, since `ipconfig` is its own application (`ipconfig.exe`) and not a command built into `cmd.exe`, your first code snippet could be simplified to `System.Diagnostics.Process.Start("ipconfig");`. – Lance U. Matthews Sep 11 '18 at 03:06
9

from codeproject

 public void ExecuteCommandSync(object command)
    {
         try
         {
             // create the ProcessStartInfo using "cmd" as the program to be run,
             // and "/c " as the parameters.
             // Incidentally, /c tells cmd that we want it to execute the command that follows,
             // and then exit.
        System.Diagnostics.ProcessStartInfo procStartInfo =
            new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

        // The following commands are needed to redirect the standard output.
        // This means that it will be redirected to the Process.StandardOutput StreamReader.
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        // Do not create the black window.
        procStartInfo.CreateNoWindow = true;
        // Now we create a process, assign its ProcessStartInfo and start it
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
        // Get the output into a string
        string result = proc.StandardOutput.ReadToEnd();
        // Display the command output.
        Console.WriteLine(result);
          }
          catch (Exception objException)
          {
          // Log the exception
          }
    }
Dzmitry Martavoi
  • 6,867
  • 6
  • 38
  • 59
  • I don't know it it's needed, but in [this answer](https://stackoverflow.com/a/29753402/1033581) they added `proc.WaitForExit();`. – Cœur Oct 22 '19 at 05:51