【问题标题】:How to execute command on cmd from C# [closed]如何从 C# 在 cmd 上执行命令 [关闭]
【发布时间】:2013-04-08 12:16:14
【问题描述】:

我想通过我的 C# 应用在 cmd 上运行命令。

我试过了:

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

结果:

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

为什么?

【问题讨论】:

  • ipconfig 只是一个exe尝试System.Diagnostics.Process.Start('ipconfig');
  • ipconfig 这里可以表示使用字符串生成器或其他不可能进行硬编码的机制构建的复杂命令。

标签: c# cmd


【解决方案1】:

使用

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

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

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

【讨论】:

  • 然后如何发送未来的命令?
  • 人们在命令调用前加上cmd /c 是很常见的,尽管这并不总是必要的。在这种情况下,由于 ipconfig 是它自己的应用程序 (ipconfig.exe),而不是内置于 cmd.exe 中的命令,因此您的第一个代码 sn-p 可以简化为 System.Diagnostics.Process.Start("ipconfig");
【解决方案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
          }
    }

【讨论】:

  • 我不知道它是必需的,但他们在this answer 中添加了proc.WaitForExit();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-01
  • 2019-01-13
  • 1970-01-01
  • 2011-07-24
  • 2016-06-17
  • 2021-02-19
相关资源
最近更新 更多