在cmd上执行两条命令

问题描述 投票:0回答:2

我编写测试控制台程序。该程序使用两行命令执行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();
}
c# batch-file
2个回答
2
投票

使用

&
运算符。

例如:

dir & echo foo

给你的:

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

另请参阅:如何在 Windows CMD 中一行运行两个命令?


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");
方法,这有效。

© www.soinside.com 2019 - 2024. All rights reserved.