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.
System.IO.StreamReader
has a method calledReadLine
which would be what you want to use: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 becauseP.HasExited
now becametrue
.