c#run命令不执行命令

时间:2012-12-24 11:18:22

标签: c# command-line process

我想运行这个:

string command = "echo test > test.txt";
System.Diagnostics.Process.Start("cmd.exe", command);

它不起作用,我做错了什么?

2 个答案:

答案 0 :(得分:13)

您缺少将/C开关传递给cmd.exe以表示您要执行命令。另请注意,该命令放在双引号中:

string command = "/C \"echo test > test.txt\"";
System.Diagnostics.Process.Start("cmd.exe", command).WaitForExit();

如果您不想看到shell窗口,可以使用以下内容:

string command = "/C \"echo test > test.txt\"";
var psi = new ProcessStartInfo("cmd.exe")
{
    Arguments = command,
    UseShellExecute = false,
    CreateNoWindow = true
};

using (var process = Process.Start(psi))
{
    process.WaitForExit();
}

答案 1 :(得分:0)

这应该让你开始:

//create your command
string cmd = string.Format(@"/c echo Hello World > mydata.txt");
//prepare how you want to execute cmd.exe
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
psi.Arguments = cmd;//<<pass in your command
//this will make echo's and any outputs accessiblen on the output stream
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process p = Process.Start(psi);
//read the output our command generated
string result = p.StandardOutput.ReadToEnd();