0

I want to run this:

string command = "echo test > test.txt";
System.Diagnostics.Process.Start("cmd.exe", command);

It's not working, what am I doing wrong?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Dasher Labs
  • 99
  • 1
  • 3
  • 10

2 Answers2

13

You are missing to pass the /C switch to cmd.exe to indicate that you want to execute a command. Also notice that the command is put in double quotes:

string command = "/C \"echo test > test.txt\"";
System.Diagnostics.Process.Start("cmd.exe", command).WaitForExit();

And if you don't want to see the shell window you could use the following:

string command = "/C \"echo test > test.txt\"";
var psi = new ProcessStartInfo("cmd.exe")
{
    Arguments = command,
    UseShellExecute = false,
    CreateNoWindow = true
};

using (var process = Process.Start(psi))
{
    process.WaitForExit();
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

This should sort of get you started:

//create your command
string cmd = string.Format(@"/c echo Hello World > mydata.txt");
//prepare how you want to execute cmd.exe
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
psi.Arguments = cmd;//<<pass in your command
//this will make echo's and any outputs accessiblen on the output stream
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process p = Process.Start(psi);
//read the output our command generated
string result = p.StandardOutput.ReadToEnd();
gideon
  • 19,329
  • 11
  • 72
  • 113