C# 当字符串中未出现搜索字符串时,String.indexOf返回非负索引

C# 当字符串中未出现搜索字符串时,String.indexOf返回非负索引,c#,string,indexof,C#,String,Indexof,我正在分析一些日志文件以生成报告,但在几行中使用String.IndexOf得到奇怪的结果。这里使用C。最容易用一些代码解释 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 resul

我正在分析一些日志文件以生成报告,但在几行中使用String.IndexOf得到奇怪的结果。这里使用C。最容易用一些代码解释

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;
预期:-1实际:11

这种情况只发生在大约1 gig日志文件中的2行中

实际实现方法

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;
}
换行代码

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();}

将ctIndex设置为line.SubString后,您的方法不会检查ctIndex是否等于-1。然后将CaptureTime=的长度添加到ctIndex,然后预生成一个子字符串


由于这些原因,我怀疑您当前状态下的代码对于不包含CaptureTime=值的日志消息无法正常工作。这是功能性行为吗

您没有处理在字符串右侧找不到CaptureTime=的情况

您有ctIndex=-1,然后将CaptureTime=的长度加上12。这给了你11分。 然后,找到之后的第一个空格,即时间戳和localhost之间的空格。在15号位置。 然后,得到从11到15的子串,即4:19。 最后,您尝试将其解析为long,但显然不是。
您需要实际检查ctIndex==-1,然后正确处理它。

您使用多线程吗?提供的代码片段对您也有问题吗?给我们看看你真正的代码。我试过了,它按预期返回-1。当子字符串CaptureTime=在字符串中不存在时,如何获取其索引?祝你过得愉快:@PicrofoEGY-这正是他的问题。当子串不存在时,他从索引中得到一个值。谢谢!!!!!!!!!!!!!!!!!!!!错过了那件事,我觉得很傻。我显然需要更多的咖啡。