我编写测试控制台程序。该程序使用两行命令执行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();
}
答案 0 :(得分:2)
使用&
运算符。
例如:
dir & echo foo
对于你的:
cd c:\\test & echo 'Hello world' > test.txt
答案 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");
方法,这可行。