【发布时间】:2014-10-02 10:15:06
【问题描述】:
我有一个控制台应用程序,它执行一些命令并输出一些日志。
我需要显示命令及其结果的输出,如下所示:
>Loading the database...
>mysql -uUser -pPassword myDbName < mydumpFile
ERROR 1045 (28000): Access denied for user 'User'@'localhost' (using password: Y
ES)
>End loading the databse...
我做了以下操作:
void ImportData()
{
Program.Log("INFO", "Start importing data... <<<");
Process myProcess = new Process();
string mySqlArgs = string.Format(" -u{0} -p{1} {2} < \"{3}\"",
bddUser, bddPassword, databaseName, dumpPath);
ProcessStartInfo myProcessStartInfo =
new ProcessStartInfo("mysql", mySqlArgs);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
StreamReader reader = myProcess.StandardOutput;
string theOutput = reader.ReadToEnd();
if (theOutput.Length > 0)
Program.Log("SQL", theOutput);
Program.Log("INFO", "END importing data >>>");
}
但是这段代码
1) 不显示命令本身(仅显示结果)
2)请求可能格式错误,因为结果就像mysql命令中的格式错误
更新:新代码稍微好一点
Program.Log("INFO", "Start importing Materials... <<<".Fill(code));
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 "mysql -uUser -pPassword base < dump" */
string mySqlCommand = "mysql -u{0} -p{1} {2} < \"{3}\"";
cmd.StandardInput.WriteLine(mySqlCommand, bddUser, bddPassword, databaseName, dumpPath);
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
StreamReader reader = cmd.StandardOutput;
string theOutput = reader.ReadToEnd();
if (theOutput.Length > 0)
Program.Log("SQL", Environment.NewLine + theOutput);
Program.Log("INFO", "END importing Materials >>>".Fill(code));
,但无论如何,它会显示来自 cmd.exe 第一次执行(before mysql 命令)以及命令行after mysql 命令结果的附加信息...
【问题讨论】:
标签: c# mysql .net command-line