的问题,使用C#在cmd中执行命令 [英] Problem, executing commands in cmd using c#

查看:180
本文介绍了的问题,使用C#在cmd中执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要执行的命令提示符下面的命令



  C:\MySQL\MySQL服务器5.0\斌>的mysql -uroot -ppassword< D:/admindb/aar.sql 

当我这样做在cmd中手动,我得到我的结果



现在我试图做到这一点编程,从C#代码CMD执行它。



我我使用下面的代码来做到这一点。我没有得到任何错误,结果!!!



当我调试,我得到的字符串命令行的值,如下,

 \C:\\MySQL\\MySQL服务器5.0\\bin\\\-uroot -ppassword> \D:/admindb/AAR12.sql

我想这个问题是这个字符串,传递给CMD。如何解决这个??

 公共无效执行()
{
串命令行=\+ MySqlCommandPath +\+-u+ DbUid +-p+ DbPwd +> +\+ Path.Combine(Path_Backup,FileName_Backup + ExcID +的.sql);
System.Diagnostics.ProcessStartInfo PSI =新System.Diagnostics.ProcessStartInfo(cmd.exe的);
PSI.RedirectStandardInput = TRUE;
PSI.RedirectStandardOutput = TRUE;
PSI.RedirectStandardError = TRUE;
PSI.UseShellExecute = FALSE;
的System.Diagnostics.Process P = System.Diagnostics.Process.Start(PSI);
System.IO.StreamWriter SW = p.StandardInput;
就是System.IO.StreamReader SR = p.StandardOutput;
SW.WriteLine(命令行);
SW.Close();
}


解决方案

我用面向更对象

计算策略为同一任务。



我读使用一个StreamReader文件,并使用控制台重定向直接注射文本到MySQL exe文件。 。就像一个魅力



更新:下面是代码,它不是VB C#,但应该很容易翻译。
我用这个代码来创建一些单元测试的空分贝。在刚开始从命令行的MySQL与文件作为输入的优点是,



一)创建一个例外,如果事情失败,结果
B),你可以轻松使用此代码来控制MySQL的,而无需真正的文件。结果
C)在TestProject如果异常被抛出,你从MySQL在TestProtocol得到错误直接输出。



请注意,用户名,用户名,密码,架构是共享的属性在我的课,你可以只使用字符串替换它们或修改函数调用。

 公共共享子SetupDatabase()

'基本配置
尺寸INFILE作为字符串=..\ ..\..\MyProject\initial_db.sql
昏暗mysql_binary作为字符串=的mysql.exe
昏暗mysql_args为String =的String.Format( - ^ h {0} -u {1} {-p 2} {3},主机名,用户名,密码架构)

'创建一个从INFILE
昏暗的读者一个StreamReader作为新的StreamReader(INFILE)

'创建过程
昏暗数p作为新工艺()
p.StartInfo.FileName = mysql_binary
p.StartInfo.Arguments = mysql_args

重定向输入/输出/标准错误
p.StartInfo.RedirectStandardOutput = TRUE
p.StartInfo.RedirectStandardError = TRUE
p.StartInfo.RedirectStandardInput = TRUE
p.StartInfo.UseShellExecute =假
p.StartInfo.CreateNoWindow = TRUE
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

'启动过程
p.Start()

'从infile中读取并把它传递到MySQL
执行虽然reader.EndOfStream =假
p.StandardInput.WriteLine(reader.ReadLine)


'接近标准输入
p.StandardInput.Close()

'从标准输出/标准错误
昏暗的阅读标准输出的String = p.StandardOutput.ReadToEnd()
暗淡标准错误的String = p.StandardError.ReadToEnd()

'等待MySQL的停止
p.WaitForExit()

',如果退出码!= 0我们提高一个例外,包括标准错误
的输出。如果p.ExitCode<> 0,那么
抛出新的异常(初始DB设置失败,退出码与& p.ExitCode&安培;:&放大器; vbNewLine&安培;标准错误)
端如果

p .Close()
reader.Close()

端子


I need to execute the below command in command prompt.

C:\MySQL\MySQL Server 5.0\bin>mysql -uroot -ppassword < d:/admindb/aar.sql

When i do this manually in cmd, i am getting my results.

Now i am trying to do this programatically, to execute it in cmd from c# code.

I am using the below code to do it. I am not getting any errors and Result !!!

When i debug, i get the value of string commandLine as below,

"\"C:\\MySQL\\MySQL Server 5.0\\bin\\\" -uroot -ppassword > \"D:/admindb/AAR12.sql"

I guess the problem is with this string, passed to cmd. How to solve this ??.

public void Execute()
{
    string commandLine = "\"" + MySqlCommandPath + "\"" + " -u" + DbUid + " -p" + DbPwd + " > " + "\"" + Path.Combine(Path_Backup, FileName_Backup + ExcID + ".sql");
    System.Diagnostics.ProcessStartInfo PSI = new System.Diagnostics.ProcessStartInfo("cmd.exe");
    PSI.RedirectStandardInput = true;
    PSI.RedirectStandardOutput = true;
    PSI.RedirectStandardError = true;
    PSI.UseShellExecute = false;
    System.Diagnostics.Process p = System.Diagnostics.Process.Start(PSI);
    System.IO.StreamWriter SW = p.StandardInput;
    System.IO.StreamReader SR = p.StandardOutput;
    SW.WriteLine(commandLine);
    SW.Close();
}

解决方案

I used a more object oriented approch for the same task.

I read the file using a StreamReader and use console redirection to directly injecting the text to the mysql exe file. Works like a charm.

Update: Here is the code, it's VB not C# but should be easy to translate. I use this code to create an empty db for some unit tests. The advantage over just starting mysql from the commandline with an file as input is that

a) I create an exception if something fails
b) You could easily use this code to control mysql without needing a real file.
c) In a TestProject if the Exception is thrown you get the error output from mysql directly in your TestProtocol.

Please note that UserName, UserName, Password, Schema are Shared Properties in my class, you can just replace them with strings or modify the function call.

Public Shared Sub SetupDatabase()

    ' basic configuration
    Dim infile As String = "..\..\..\MyProject\initial_db.sql"
    Dim mysql_binary As String = "mysql.exe"
    Dim mysql_args As String = String.Format("-h {0} -u{1} -p{2} {3}", HostName, UserName, Password, Schema)

    ' Creates a StreamReader from infile
    Dim reader As New StreamReader(infile)

    ' Create the process
    Dim p As New Process()
    p.StartInfo.FileName = mysql_binary
    p.StartInfo.Arguments = mysql_args

    ' Redirect input/output/stderr
    p.StartInfo.RedirectStandardOutput = True
    p.StartInfo.RedirectStandardError = True
    p.StartInfo.RedirectStandardInput = True
    p.StartInfo.UseShellExecute = False
    p.StartInfo.CreateNoWindow = True
    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

    ' start the process
    p.Start()

    ' read from infile and pass it to mysql
    Do While reader.EndOfStream = False
        p.StandardInput.WriteLine(reader.ReadLine)
    Loop

    ' close stdin
    p.StandardInput.Close()

    ' read from stdout / stderr
    Dim stdout As String = p.StandardOutput.ReadToEnd()
    Dim stderr As String = p.StandardError.ReadToEnd()

    ' wait for mysql to stop
    p.WaitForExit()

    ' if exitcode != 0 we raise an exception and include the output from stderr
    If p.ExitCode <> 0 Then
        Throw New Exception("Initial DB Setup failed with Exitcode " & p.ExitCode & ":" & vbNewLine & stderr)
    End If

    p.Close()
    reader.Close()

End Sub

这篇关于的问题,使用C#在cmd中执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆