C#使用Process类从自定义命令捕获命令行输出

时间:2018-11-30 14:40:19

标签: c# command-line cmd

对于Windows应用程序,我有自己的自定义命令,可以在应用程序中执行特定操作,它会生成输出并将其显示在命令提示符下,以指示特定操作是否已完成,或者由于某种原因而显示错误消息。

以下是我的应用的示例自定义命令:

C:\ProgramFiles\SampleApp> START MYAPP \TEST \GETDATA "SAMPLE.TXT"
Authorization successful.
Data retrieved successfully.

C:\ProgramFiles\SampleApp> START MYAPP \TEST \GETDAATA "SAMPLE.TXT"
Authorization successful.
Invalid command parameter.

现在,我尝试使用Process类捕获此输出,但最终一直都是空字符串。 (我已经尝试了所有可能性,例如调用OutputDataReceived事件,使用StandaradOutput等)。

下面是我尝试读取命令行输出的示例。

                    Process cliProcess = new Process();
                    cliProcess.StartInfo.FileName = meter.MeterIpAddress;                        
                    cliProcess.StartInfo.FileName = "cmd.exe";
                    cliProcess.StartInfo.Arguments = "START \TEST \GETDATA "SAMPLE.TXT";
                    cliProcess.StartInfo.WorkingDirectory = !string.IsNullOrWhiteSpace(workingDirectory) ? workingDirectory : string.Empty;
                    cliProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    cliProcess.StartInfo.UseShellExecute = false;
                    cliProcess.StartInfo.RedirectStandardOutput = true;
                    cliProcess.StartInfo.RedirectStandardError = true;
                    cliProcess.StartInfo.CreateNoWindow = true;
                    cliProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    cliProcess.Exited += CliProcess_Exited;
                    cliProcess.OutputDataReceived += new DataReceivedEventHandler(CliProcess_OutputDataReceived);
                    cliProcess.ErrorDataReceived += CliProcess_ErrorDataReceived;
                    cliProcess.EnableRaisingEvents = true;
                    cliProcess.Start();
                    cliProcess.BeginOutputReadLine();
                    cliProcess.BeginErrorReadLine();

private void CliProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
                   {
                      if (e.Data != null)
                      {
                          temp.AppendLine(e.Data);
                      }

                   }

private void CliProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (e.Data != null)
        {
            temp.AppendLine(e.Data);
        }
    }

还有其他方法吗?

0 个答案:

没有答案
相关问题