在cmd上执行两个命令

时间:2014-04-03 12:48:55

标签: c# batch-file

我编写测试控制台程序。该程序使用两行命令执行cmd。但它怎么做? 如何编写更简单的代码而不是这个大代码?

String command = @"cd c:\\test";//command get to current folder 
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = command;
startInfo.RedirectStandardOutput = true;
using (Process exeProcess = Process.Start(startInfo))
{
    exeProcess.WaitForExit();
}
String command = @"echo 'Hello world' > test.txt";//command write Hello world to text file
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = command;
startInfo.RedirectStandardOutput = true;
using (Process exeProcess = Process.Start(startInfo))
{
    exeProcess.WaitForExit();
}

2 个答案:

答案 0 :(得分:2)

使用&运算符。

例如:

dir & echo foo

对于你的:

cd c:\\test & echo 'Hello world' > test.txt

另见:How to run two commands in one line in Windows CMD?

答案 1 :(得分:0)

您可以将命令放在批处理文件yourcmd.bat中,在您的情况下yourcmd.bat会这样:

cd c:\test
echo "Hello world" > test.txt

cd c:\test & echo "Hello world" > test.txt

然后你可以调用System.Diagnostics.Process.Start("yourcmd.bat");方法,这可行。