问题
so , i have this working code to display ping and statistics from System.Diagnostics.Process
Process P = new Process();
P.StartInfo.FileName = "ping";
P.StartInfo.Arguments = "-c 3 8.8.8.8"; // Take 3 samples to 8.8.8.8
P.StartInfo.UseShellExecute = false;
P.StartInfo.RedirectStandardOutput = true;
string readData = "";
if (P.Start())
readData = P.StandardOutput.ReadToEnd(); // This will also wait for the process to at least close its stdout
Console.Write(readData.ToString()); // Doing this, you will see how the
and i process the string in this way :
List<string> Lines = new List<string>(readData.Replace("\r\n", "\n").Split('\n'));
while (Lines.Count > 0 && !Lines[0].StartsWith("---"))
{
Match M = Regex.Match(Lines[0], @"^[\d]+ bytes from ([^:]+): [^ ]+ ttl=([\d]+) time=([^ ]+) ms");
if (M != null && M.Success)
{
string IP = M.Groups[1].Value;
string TTL = M.Groups[2].Value;
string timeStr = M.Groups[3].Value;
Console.WriteLine(String.Format("Ping to {0} took {2} ms with a ttl of {1}", IP, TTL, timeStr));
// Parsing the timeStr will work the same way as above
}
Lines.RemoveAt(0);
}
ReadToEnd(); wait until the standart output is closed and then process the string.
My question is how to process the string line per line in real time and how to stop the process in certain time and to get the statistics too in the end.
回答1:
System.IO.StreamReader has a method called ReadLine which would be what you want to use:
if (P.Start()){
DateTime endTime = DateTime.Now.AddSeconds(5);
while(!P.HasExited){
readData = P.StandardOutput.ReadLine(); // This will wait for the next line to be output completely
Match M = Regex.Match(Lines[0], @"^[\d]+ bytes from ([^:]+): [^ ]+ ttl=([\d]+) time=([^ ]+) ms");
if (M != null && M.Success)
{
string IP = M.Groups[1].Value;
string TTL = M.Groups[2].Value;
string timeStr = M.Groups[3].Value;
Console.WriteLine(String.Format("Ping to {0} took {2} ms with a ttl of {1}", IP, TTL, timeStr));
}
if (endTime > DateTime.Now)
P.Kill();
}
}
I introduced a variable called endTime that gets initialized with a time 5 seconds in the future, and when that time has been reached, the process gets killed causing your loop to terminate because P.HasExited now became true.
来源:https://stackoverflow.com/questions/42892207/how-to-read-from-output-in-real-time-and-stop-at-certain-time-if-needed