How to use mysql.exe from C#
I need to call the following command from C# code: mysql.exe --user=useranme --password=password --database=base < C:\backups\data.sql
I use:
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.FileName = "mysql.exe";
process.StartInfo.Arguments = "--user=useranme --password=password --database=base < C:\backups\data.sql";
process.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEvent开发者_JS百科Args args)
{
Console.WriteLine(args.Data);
});
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
But it does not work as a direct entry to the command line. I see that the right part "< C:\backups\data.sql" is not executed.
Help please.
this is because writing < filename at the command prompt force the shell to submit the content of the file c:\backups\data.sql in the standard input of your program. Passing the part after the '<' in the argument is not correct because you have to feed the stdin of your executable whith the content of the file.In order to do stdin/stdout redirection you can refer this question:
Redirecting stdin and stdout where stdin closes first
and you will push the content of your data.sql file onto the stdin stream.
Just something I noticed, could it be that your database is not called data.sql
but somehow else, where first letter matches some escape sequence?
You need to escape all \
characters in path or C# compiler will treat them as escape sequences.
In your code, "C:\backups"
actually becomes C:□ackups
.
You either need to prefix string with @
which tells compiler to not use escape sequences, or else prefix \
with another \
:
process.StartInfo.Arguments = @"--user=useranme --password=password --database=base < C:\backups\data.sql";
process.StartInfo.Arguments = "--user=useranme --password=password --database=base < C:\\backups\\data.sql";
However it is just as possible that you just typed some path here and your code doesn't have this mistake.
See the answer by SchlaWiener here:
Problem, executing commands in cmd using c#
It worked for me! :)
精彩评论