我目前正在开发 C# 程序。该项目的一部分涉及将 SQL 文件通过管道传输到 MySQL 程序中,以将文件恢复到数据库中。
下面是我正在使用的代码。
command = string.Format("--host={0} --user={1} --password={2} --port={3} {4} < {5}",
MySQLConnectionManager.currentlyUsingConnection[MySQLConnectionManager.ConnectionKeyStrings.SERVER],
MySQLConnectionManager.currentlyUsingConnection[MySQLConnectionManager.ConnectionKeyStrings.USERNAME],
MySQLConnectionManager.currentlyUsingConnection[MySQLConnectionManager.ConnectionKeyStrings.PASSWORD],
MySQLConnectionManager.currentlyUsingConnection[MySQLConnectionManager.ConnectionKeyStrings.PORT],
db.database, restoreFile);
Process process = new Process();
process.StartInfo.UseShellExecute = false;
//process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.FileName = @"C:\Program Files\MySQL\MySQL Server 5.5\bin\mysql.exe";
process.StartInfo.Arguments = command;
process.StartInfo.CreateNoWindow = true;
process.Start();
//string output = process.StandardOutput.ReadToEnd();
string errorOutput = process.StandardError.ReadToEnd();
不过,我没有收到任何错误,如果我重定向标准输出,我只会返回文件的内容,而不是实际执行恢复。
最佳答案
在 shell 中,<
将给定文件的内容通过管道传输到命令的标准输入中。但是,由于您设置了 process.StartInfo.UseShellExecute = false;
,这意味着该命令不会像 shell 脚本一样被解释,并且所有输入/输出重定向都必须通过 .NET 接口(interface)完成。
选项 1:使用 .NET 接口(interface)
您需要将文件内容写入 process.StandardInput
。不幸的是,process.StandardInput
是一个 StreamWriter,我知道没有简单的方法可以将文件内容复制到 StreamWriter 中。也许在文件的 FileStream 上使用 CopyToAsync 并将其发送到 StandardInput.BaseStream 可能会起作用。
选项 2:使用 Shell 接口(interface)
现在,您需要 UseShellExecute = false
为了 RedirectStandardError = true
才能生效。另一种方法是在命令行中将 StdErr 重定向到 StdOut,并设置 UseShellExecute = false
。您可以通过将格式字符串更改为:
"--host={0} --user={1} --password={2} --port={3} {4} < {5} 2>&1"
但是,这可能会产生其他副作用,例如需要用户名才能运行。
免责声明:我尚未实际测试过这些解决方案。它们可能有效,也可能无效。
关于c# - 通过C#恢复MySQL文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23702548/