0

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();
}
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
user3231442
  • 600
  • 1
  • 9
  • 25

2 Answers2

2

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?

Community
  • 1
  • 1
Derek
  • 7,615
  • 5
  • 33
  • 58
0

you can put you command in a batch file yourcmd.bat, in your case the yourcmd.bat will like this:

cd c:\test
echo "Hello world" > test.txt

or

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

then you can just call System.Diagnostics.Process.Start("yourcmd.bat"); method, this works.

Will Wang
  • 537
  • 5
  • 7