Fastest way to find strings in a file

后端 未结 5 1377
耶瑟儿~
耶瑟儿~ 2021-01-18 23:04

I have a log file that is not more than 10KB (File size can go up to 2 MB max) and I want to find if atleast one group of these strings occurs in the files. These strings w

5条回答
  •  终归单人心
    2021-01-18 23:35

    Here's one possible way to do it:

    StreamReader sr;
    string fileContents;
    
    string[] logFiles = Directory.GetFiles(@"C:\Logs");
    
    foreach (string file in logFiles)
    {
    
        using (StreamReader sr = new StreamReader(file))
        {
    
            fileContents = sr.ReadAllText();
    
            if (fileContents.Contains("ACTION:") || fileContents.Contains("INPUT:") || fileContents.Contains("RESULT:"))
            {
                 // Do what you need to here
            }
    
        }
    }
    

    You may need to do some variation based on your exact implementation needs - for example, what if the word spans two lines, does the line need to start with the word, etc.

    Added

    Alternate line-by-line check:

    StreamReader sr;
    string[] lines;
    
    string[] logFiles = Directory.GetFiles(@"C:\Logs");
    
    foreach (string file in logFiles)
    {
    
        using (StreamReader sr = new StreamReader(file)
        {
    
            lines = sr.ReadAllLines();
    
            foreach (string line in lines)
            {        
                if (line.Contains("ACTION:") || line.Contains("INPUT:") || line.Contains("RESULT:"))
                {
                    // Do what you need to here
                }
            }
    
        }
    }
    

提交回复
热议问题