如何在C#控制台应用程序中执行CMD命令?

21

在Windows上,使用cmd非常简单地生成mysqldump,只需执行以下操作:

打开cmd并键入mysqldump -uroot -ppassword database > c:/data.sql

这将生成所需数据库的SQL转储文件。

我正在编写控制台应用程序,以便可以运行此命令:

-uroot -ppass databse  > location\data.sql

我尝试了以下代码,但都没有成功:

System.Diagnostics.ProcessStartInfo procStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmd); 

我该如何启动一个cmd进程并成功发送命令?


你应该详细说明错误是什么,发生了什么。也许CMD找不到,尝试在其中放入完整路径。 - Hanan
在命令行中添加密码安全吗...? - goorj
5个回答

47
Process cmd = new Process();

cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;

cmd.Start();

/* execute "dir" */

cmd.StandardInput.WriteLine("dir");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());

7

为什么不直接调用mysqldump?

ProcessStartInfo procStartInfo = 
    new ProcessStartInfo("mysqldump", "uroot ppassword databse > c:/data.sql");

如果有原因需要这样写你的代码:

If there is a reason, your code should look like this:

ProcessStartInfo procStartInfo = 
    new ProcessStartInfo("cmd", 
        "/c \"mysqldump uroot ppassword databse > c:/data.sql\"");

变更:

  • 您的cmd变量中缺少"mysqldump"。
  • 您应该将要在命令行中执行的命令放入引号中。

1
原因很简单。新手只有在完全了解一切之后才能做到这一点。我创建它是为了帮助他们,让他们可以轻松地做到这一点。 - delete my account

4

您是否使用刚刚创建的ProcessStartInfo实例运行Process.Start(psi)?

无论如何,以下代码应该可以工作:

string commandToExecute = @"c:\windows\system32\calc.exe";
Process.Start(@"cmd", @"/c " + commandToExecute);


1
那正是我正在寻找的,谢谢朋友。 - smoothumut


0

使用 Powershell,

Process cmd = new Process();

cmd.StartInfo.FileName = "powershell.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;

cmd.Start();

/* execute "dir" */

cmd.StandardInput.WriteLine("dir");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());

当你想在CMD中运行多个命令时,可以这样说:

cmd.StandardInput.WriteLine("dir && dir");

在PowerShell中,使用以下代码:
cmd.StandardInput.WriteLine("dir;dir");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接