I’m parsing some log files to make a report but getting weird results with String.IndexOf() on a few lines. Using C# here. Most easy to explain with some code.
String line = "Jun 29 14:34:19 localhost axis2_http_server: CEF:0|AOPTIX|IRIS|4.1.0.1664.2839|AD214030000301-2610017|114|SDK_ACCESS|4|time=1340980459 comp=10 compinfo=CAPTURE from=8 result=0 user=Admin thread=1305:1962 msg=ation=0.00, faceColor=11.49 HR Face is ICAO compliant, inter-pupil distance=140.00. No match found on LEFT eye (database is empty). LEFT_uid=-1, blacklist=0 No match found on RIGHT eye (database is empty). RIGHT_uid=-1, blacklist=0 CAPTURE successfully completed - SOAP response sent. ";
int ctIndex = line.IndexOf("CaptureTime=");
return ctIndex;
Expected: -1
Actual: 11
This only happens for 2 lines in about a gig of log files.
Actual implemented method
private TimeSpan parseDuration(string line)
{
int ctIndex = line.IndexOf("CaptureTime=");
ctIndex = ctIndex + "CaptureTime=".Length;
int endIndex = line.IndexOf(" ", ctIndex);
string sDuration = line.Substring(ctIndex, endIndex - ctIndex);
long duration;
if (!long.TryParse(sDuration, out duration))
{
Console.WriteLine("Error Parsing Duration");
return TimeSpan.Zero;
}
duration *= 1000;
TimeSpan tsDuration = new TimeSpan(duration*1000);
return tsDuration;
}
Line Feeding Code
try{
StreamReader sr = new StreamReader(FilePath);
string line = sr.ReadLine();
while(line != null)
{
TimeSpan ts = parseDuration(line);
line = sr.ReadLine();
}
catch(Exception ex){}
finally{sr.close();}
Your method doesn’t check if ctIndex equals -1 after setting it to line.SubString(). You’re then adding the length of “CaptureTime=” to ctIndex, then preforming a substring.
I would suspect that your code in its current state would not work properly for log messages that don’t contain a CaptureTime= value for those reasons. Is that functional behaviour intended?