0

我想运行这个:

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

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

4

2 回答 2

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();
}
于 2012-12-24T11:24:28.643 回答
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();
于 2012-12-24T11:25:35.680 回答