我编写测试控制台程序。该程序使用两行命令执行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();
}
使用
&
运算符。
例如:
dir & echo foo
给你的:
cd c:\\test & echo 'Hello world' > test.txt
您可以将命令放入批处理文件中
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");
方法,这有效。