无法从RedirectStandardOutput捕获CMD输出

时间:2014-01-30 17:21:57

标签: c# .net

我正在尝试在命令中运行具有不同值的命令(基于用户在运行时在表单文本框中键入的内容。

我见过几个不同的例子,由于例子之间存在歧义或因为类调用与我的例子不匹配而无法实现它们。

基本上,我试图让代码在命令提示符下运行命令,然后在富文本框中显示输出。到目前为止,我尝试过StreamReader尝试,但无济于事。运行时我收到错误StandardOut has not been redirected or the process hasn't started yet.

Process process = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        string contentType = "\"Content-Type:text/xml\"";
        string output = string.Empty;
        string command = @"c:\curl -s -k -H "+contentType+" -u "+txtBoxIntgrName.Text+":"+txtBoxIntgrPass.Text+" -g https://"+txtBoxDomain.Text+"/wabapps/bb-data-integrat-flatfile-BBLEARN/endpoint/dataSetStatus/"+txtBoxReferenceID.Text;
        startInfo.Arguments = "/user:Administrator \"cmd /c " + command + "\"";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo = startInfo;

        process.Start();
        using (StreamReader streamReader = process.StandardOutput)
        {
            rchTxtBoxDataSetStatus.Text = streamReader.ReadToEnd();
        }

实施我的请求的正确方法是什么?谢谢。

1 个答案:

答案 0 :(得分:1)

我只需使用

即可使用
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        string contentType = "\"Content-Type:text/xml\"";

        string command = @"C:\blackboard\apps\sis-controller\sis-data\curl -s -k -H " + contentType + " -u " + txtBoxIntgrName.Text + ":" + txtBoxIntgrPass.Text + " -g https://" + txtBoxDomain.Text + "/webapps/bb-data-integration-flatfile-BBLEARN/endpoint/dataSetStatus/" + txtBoxReferenceID.Text;
        startInfo.Arguments = "/user:Administrator \"cmd /c " + command + "\"";
        startInfo.UseShellExecute = false;
        startInfo.RedirectStandardOutput = true;
        using (Process process = Process.Start(startInfo))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                rchTxtBoxDataSetStatus.Text = result;
            }
        }

我遇到的所有其他例子都太不必要了。