c# - 如何在 C# 中逐行读取 CMD 输出结果
问题描述
我想打开 .bat 文件,为此我使用 cmd 并为参数提供输入,最后我收到整个输出结果,但我只想获得最后一个命令输出结果,所以如果有人有任何解决方案,请指导我。
using System;
using System.Diagnostics;
using System.Text;
namespace ConsoleApp
{
class Program
{
private static StringBuilder output = new StringBuilder();
private static System.Diagnostics.Process standalone = new System.Diagnostics.Process();
static void Main()
{
StartStandalone();
StartProcess();
}
private static void StartProcess()
{
try
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.CreateNoWindow = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();
process.StandardInput.WriteLine("C:\\Users\\aali\\EAP-7.2.0\\bin\\Jboss-cli.bat");
process.StandardInput.WriteLine("connect");
process.StandardInput.WriteLine("deployment-info");
process.StandardInput.Flush();
process.StandardInput.Close();
String output = "";
while (!process.StandardOutput.EndOfStream)
{
string line = process.StandardOutput.ReadLine();
if (line.Contains("RUNTIME-NAME"))
{
output += line + "\r\n" + process.StandardOutput.ReadLine() + "\r\n";
}
}
Console.WriteLine(output);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
Console.ReadLine();
}
}
private static void StartStandalone()
{
standalone.StartInfo.FileName = "C:\\Users\\aali\\EAP-7.2.0\\bin\\standalone.bat";
standalone.Start();
}
}
}
我用于此任务的代码附在上面
解决方案
您已经在读取循环中的每一行,因此一个简单的解决方案是将每一行分配给一个名为 lastLine 的变量,并且在循环完成之前不对该变量执行任何操作。
当然,这不是很有效,但需要对您的代码进行最少的更改。
string lastLine = "";
while (!process.StandardOutput.EndOfStream)
{
lastLine = process.StandardOutput.ReadLine();
}
//lastLine will now contain the value of the last line of the output
Console.WriteLine($"Last Line = {lastLine}");
推荐阅读
- python - --tf_initial_checkpoint 用于 ADE20k 数据集
- android - DataBindingUtil 加上 NavHostFragment 后退导航不起作用
- excel - 为什么在使用 IsEmpty() 方法时,使用 Len() 方法长度为 0 的单元格等于 False?
- pdf - 使用 Sphinx ImageMagick 扩展 sphinx.ext.imgconverter 更改转换后图像的分辨率
- javascript - 在javascript中过滤数组
- docker - 码头集装箱上的 Blazor
- sql - 我们可以从表中选择计数(查询)吗
- flutter - Flutter 升级后 FlatButton 边距发生变化
- powershell - 如何为csv文件批量保存UTF-8?
- python - 多个范围/np.arange