如何从c#执行cmd命令

use*_*505 5 c# cmd

我想从我的c#app在cmd上运行命令.

我试过了:

string strCmdText = "ipconfig";
        System.Diagnostics.Process.Start("CMD.exe", strCmdText);  
Run Code Online (Sandbox Code Playgroud)

结果:

cmd窗口弹出,但命令没有做任何事情.

为什么?

Pio*_*app 9

使用

System.Diagnostics.Process.Start("CMD.exe", "/C ipconfig");  
Run Code Online (Sandbox Code Playgroud)

如果你想让cmd仍然打开使用:

System.Diagnostics.Process.Start("CMD.exe", "/K ipconfig");  
Run Code Online (Sandbox Code Playgroud)

  • 人们通常会在命令调用前加上“ cmd / c”,即使这并非总是必要的。在这种情况下,由于ipconfig是其自己的应用程序(ipconfig.exe),而不是cmd.exe内置的命令,因此您的第一个代码段可以简化为System.Diagnostics.Process.Start(“ ipconfig) “);`。 (2认同)

Dzm*_*voi 9

来自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
          }
    }
Run Code Online (Sandbox Code Playgroud)