Search code examples
c#batch-file

Execute two commands on cmd


I write test console program. This program execute cmd with two line command. But how it's do? Instead of this large code, how write more easy code?

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();
}

Solution

  • Use the & operator.

    For example:

    dir & echo foo
    

    For yours:

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

    Also see: How to run two commands in one line in Windows CMD?