文本文件解析 – 如何搜索特定字符串并返回整行?

例如,txt文件有以下条目说:

england is cold country India is poor country england is cold country england is cold country India is poor country english county cricket season. 

现在我想在这个txt文件中搜索字符串“england”并返回包含该字符串的整行。 我怎么能用C sharp语言呢?

我会考虑两种方法,对于大文件(兆字节)和相对较小的方法。

大文件

如果文件很大并且包含兆字节的数据:使用流读取器,读取文件untile EndOfLine,analize只是readed字符串

 string pattern = "england"; IList result = new List(); using (var reader = new StreamReader("TestFile.txt")) { string currentLine; while ((currentLine= reader.ReadLine()) != null) { if (currentLine.Contains(pattern) { // if you do not need multiple lines and just the first one // just break from the loop (break;) result.Add(currentLine); } } } 

小文件

如果文件很小,你可以使用helper将所有文件内容作为字符串数组返回 – ( File.ReadAllLines() )每行一个字符串,然后使用LINQ搜索substring。 如果您使用的是.NET 4或更高版本,则可以利用新的帮助程序( File.ReadLines() ),它不会读取整个文件并读取为deffered操作。

.NET 2.0 – 3.5:

 string pattern = "england"; IEnumerable result = File.ReadAllLines() .Where(l => l.Contains(pattern)); 

.NET4 – 4.5:

 string pattern = "england"; IEnumerable result = File.ReadLines() .Where(l => l.Contains(pattern)); 

如果你只需要第一行使用.FirstOrDefault(l => l.Contains(pattern))而不是Where(l => l.Contains(pattern))

MSDN :

ReadLines和ReadAllLines方法的不同之处如下:使用ReadLines时,可以在返回整个集合之前开始枚举字符串集合; 当您使用ReadAllLines时,必须等待返回整个字符串数组才能访问该数组。 因此,当您使用非常大的文件时,ReadLines可以更高效。

你可以这样做。 如果要返回带有“england”的所有行,则需要创建一个字符串列表并返回该值。

 foreach(string line in File.ReadAllLines("FILEPATH")) { if(line.contains("england")) return line; } return string.empty; 

1)阅读所有行。 http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx

2)创建一个字符串列表来填充匹配项

3)使用IndexOf(matchstring)> -1循环或linq行并查找匹配

4)返回结果