20

It's very simple to make a mysqldump in cmd on windows, simply:

Open cmd and put type mysqldump uroot ppassword database > c:/data.sql

This results in an SQL dump file for the desired database.

I'm writing a console application so I may run this command:

-uroot -ppass databse  > location\data.sql

I tried the following code to no avail:

System.Diagnostics.ProcessStartInfo procStartInfo =
    new System.Diagnostics.ProcessStartInfo("cmd", "/c " + cmd); 

How might I start a cmd process and send my command successfully?

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129

5 Answers5

46
Process cmd = new Process();

cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;

cmd.Start();

/* execute "dir" */

cmd.StandardInput.WriteLine("dir");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
Silx
  • 2,663
  • 20
  • 21
7

Is there a reason why you don't call mysqldump directly?

ProcessStartInfo procStartInfo = 
    new ProcessStartInfo("mysqldump", "uroot ppassword databse > c:/data.sql");

If there is a reason, your code should look like this:

ProcessStartInfo procStartInfo = 
    new ProcessStartInfo("cmd", 
        "/c \"mysqldump uroot ppassword databse > c:/data.sql\"");

Changes:

  • You where missing "mysqldump" in your cmd variable.
  • You should put the command to be executed in the command line into quotes.
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • 1
    reason is simple. newbie never can do that whenever they not know everything properly. i make it to help them then they can easily do that. –  Apr 07 '11 at 01:07
3

Do you run Process.Start(psi) with the ProcessStartInfo instance you have just created?

Anyway, the following should do the work:

string commandToExecute = @"c:\windows\system32\calc.exe";
Process.Start(@"cmd", @"/c " + commandToExecute);

Igor S.
  • 553
  • 4
  • 10
1

Executing Batch File in C#

Check it out.

Community
  • 1
  • 1
Wessel T.
  • 2,280
  • 2
  • 20
  • 29
0

To use Powershell,

Process cmd = new Process();

cmd.StartInfo.FileName = "powershell.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;

cmd.Start();

/* execute "dir" */

cmd.StandardInput.WriteLine("dir");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());

when you wish to run several commands in CMD say,

cmd.StandardInput.WriteLine("dir && dir");

while in powershell, use:

cmd.StandardInput.WriteLine("dir;dir");
Joseph Wambura
  • 2,732
  • 2
  • 21
  • 24