如何从 C# 在 cmd 上执行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15878810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:15:32  来源:igfitidea点击:

How to execute command on cmd from C#

c#cmd

提问by user2257505

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

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

I tried:

我试过:

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

result:

结果:

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

cmd 窗口弹出,但该命令没有执行任何操作。

why?

为什么?

采纳答案by Piotr Stapp

Use

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

If you want to have cmd still opened use:

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

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

回答by Dzmitry Martavoi

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