CMD结果进入DropDownList

时间:2015-05-14 08:34:38

标签: c# winforms sqlcmd

我正在尝试创建一个恢复数据库的安装程序,我想将cmd命令sqlcmd -L的结果返回到按钮点击事件的下拉选项中。

有没有可能的方法来实现这一点,而不将命令的输出发送到file.txt并在之后读取每一行?

private void button1_Click(object sender, EventArgs e)
{
    string command;
    command = "sqlcmd -L " ;

    try
    {
        System.Diagnostics.ProcessStartInfo procStartInfo =
        new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        procStartInfo.CreateNoWindow = false;

        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();

       //Get the result and populate the drop down
    }
    catch (Exception objException)
    {
        // Log the exception
    }
}

2 个答案:

答案 0 :(得分:1)

不确定这是否是您所需要的,但Process类具有StandardOutput属性,允许您通过该进程将数据转储到标准输出(通常是控制台)。因此,在该过程完成后(使用proc.WaitForExit()),您可以这样做:

string processOutput = proc.StandardOutput.ReadToEnd();

然后,如果您需要单独处理每一行,您可以执行以下操作:

var lines = processOutput.Split(
    new[] {Environment.NewLine},
    StringSplitOptions.RemoveEmptyEntries);
foreach(var line in lines) { ... }

答案 1 :(得分:0)

简而言之,您正在谈论进程间通信。有很多可用的机制,请看这里。

https://msdn.microsoft.com/en-us/library/windows/desktop/aa365574%28v=vs.85%29.aspx