首页 > 解决方案 > C# 使用 Process 类从自定义命令中捕获命令行输出

问题描述

我有我自己的自定义命令供我的 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);
        }
    }

还有什么办法吗?

标签: c#command-linecmd

解决方案


推荐阅读