如何从C#上CMD执行命令[关闭](how to execute command on cmd fr

2019-08-20 07:37发布

我想从我的C#应用​​程序上运行CMD命令。

我试过了:

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

结果:

cmd窗口弹出,但该命令没有做什么。

为什么?

Answer 1:

使用

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

如果你想有CMD打开仍在使用:

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


Answer 2:

从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
          }
    }


文章来源: how to execute command on cmd from c# [closed]
标签: c# cmd