Fastest way to find strings in a file

后端 未结 5 1286
耶瑟儿~
耶瑟儿~ 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:41

    This code sample searches for strings in a large text file. The words are contained in a HashSet. It writes the found lines in a temp file.

            if (File.Exists(@"temp.txt")) File.Delete(@"temp.txt");
    
            String line;
            String oldLine = "";
            using (var fs = File.OpenRead(largeFileName))
            using (var sr = new StreamReader(fs, Encoding.UTF8, true))
            {
                HashSet hash = new HashSet();
                hash.Add("house");
                using (var sw = new StreamWriter(@"temp.txt"))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        foreach (String str in hash)
                        {
                            if (oldLine.Contains(str))
                            {
                                sw.WriteLine(oldLine); 
                                // write the next line as well (optional)
                                sw.WriteLine(line + "\r\n");                                    
                            }
                        }
                        oldLine = line;
                    }
                }
            }
    

提交回复
热议问题