【问题标题】:Loading a cmd in a console application在控制台应用程序中加载 cmd
【发布时间】: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


    【解决方案1】:

    执行脚本为

     mysql -vvv -uUser ...
    

    此选项将在脚本执行期间显示查询。

    至于你的其他问题:你为什么调用 cmd.exe?只需直接从您的程序中调用 mysql.exe 并跳过 shell...

    【讨论】:

    • 如果我直接调用mysql exe,我不会在输出中看到命令本身,不是吗?就像我实际上没有看到“cmd.exe”一样......
    • 我不需要看 sql 命令。我需要就像在帖子中看到的那样,命令,如果不正常,最终会出现错误(对于日志)。
    猜你喜欢
    • 2015-08-17
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多