C# 在cmd上执行两个命令
我编写了测试控制台程序。该程序使用两行命令执行cmd。但这是怎么回事? 如何编写更简单的代码,而不是编写这么大的代码C# 在cmd上执行两个命令,c#,batch-file,C#,Batch File,我编写了测试控制台程序。该程序使用两行命令执行cmd。但这是怎么回事? 如何编写更简单的代码,而不是编写这么大的代码 String command = @"cd c:\\test";//command get to current folder ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; start
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
或
然后您可以调用System.Diagnostics.Process.Start(“yourcmd.bat”)代码>方法,这是有效的
cd c:\test & echo "Hello world" > test.txt