我有一个控制台应用程序,它执行一些命令并输出一些日志。
我需要显示命令及其结果的输出,如下所示:
>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 第一次执行(mysql 命令之前)的附加信息,以及 mysql 命令结果之后的命令行...
最佳答案
执行脚本
mysql -vvv -uUser ...
此选项将在脚本执行期间显示查询。
至于你的另一个问题:为什么你要调用cmd.exe?只需直接从程序中调用 mysql.exe 并跳过 shell...
关于c# - 在控制台应用程序中加载 cmd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26158737/