Search code examples
c#.netmysqlstartprocessinfo

Why is dumping MySQL database programmatically different from dumping via command line?


To dump database from command line, all I need to do is:

mysqldump -uroot --password=  myDb --routines> "C:\s.sql"

So all I would try programmatically is this, which is the direct interpretation of it I suppose:

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = dumpUtilityPath;
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;

psi.Arguments = "-uroot --password=  myDb --routines> \"C:\\s.sql\"";

Process process = Process.Start(psi);
process.WaitForExit();
process.Close();

Which doesn't work at all. Instead I have to go for this which one can find all over the net, which works too.

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = dumpUtilityPath;
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;

psi.Arguments = string.Format("-R -u{0} --password={1} -h{2} {3} --routines", "root", "", "localhost", "myDb");

Process process = Process.Start(psi);
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Close();

using (StreamWriter writer = new StreamWriter("C:\\s.sql"))
{
    writer.WriteLine(output);
    writer.Close();
}
  1. Why is that I need to use stream writer to get the database in an sql file which I can do otherwise directly from commands in command prompt?

  2. What is the role of -R in the second block?


Solution

  • What you are doing in the command line version is using the shell to pipe the standard output to a file (the > command, followed by a file name, is a shorthand way of saying "take all of the standard output of this program and write it to this file"). To do the same thing from C#, you need to hand the standard output yourself and write it to a file.

    The -R in the second example seems duplicative. According to this page, it is the same as --routines. Have you tried it without?