【发布时间】:2021-08-08 09:59:28
【问题描述】:
我想打开 .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();
}
}
}
我用于此任务的代码附在上面
【问题讨论】:
-
要获取最后一行,您可以使用 Indexof("\n") 然后使用 SubString(index) 从最后返回到文件末尾读取。 bat 文件输出很可能以返回结束,因此您需要获得倒数第二个返回。
-
i want to get just last command output results你必须为此编写代码。进程的输出是字符流,而不是数组或行列表。许多甚至没有任何换行符,或者应用程序可能会在发出换行符之前延迟。 Process.StandardOutput 是进程输出之上的 StreamWriter,它允许您逐行读取文本。如果进程延迟发送换行符,ReadLine将阻塞 -
您可以使用OutputDataReceived 事件来检索收到的行,并只保留最新的。
标签: c# asp.net batch-file cmd