c# - 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);
}
}
还有什么办法吗?
解决方案
推荐阅读
- php - PHP:如何在完全写入之前开始提供正在写入的文件?
- reactjs - 在 React 中执行 API 调用之前检查 setState 是否已运行
- python - 如何将嵌套的字符串列表转换为一个列表?
- sql - 如何在 Oracle 中得到正确的总和结果
- javascript - JavaScript 查找是否有任何具有特定类的 div 被悬停,然后识别确切的 div
- python - 使用 OOP Python 读取 CSV
- reactjs - React 组件与函数,我应该使用什么,为什么?
- android - 访问 EditText ID 数据返回 Null
- debugging - 如何在 web2py 中启用调试?
- python - 在不同列中比较 Pandas DataFrame 中的前行值