我会考虑两种方法,大文件(兆字节)和相对较小。
大文件
如果文件较大,包含兆字节的数据:使用流读取器,读取文件取消平铺行尾,analize只是readed串
string pattern = "england";
IList<string> result = new List<string>();
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);
}
}
}
小文件
如果一个文件小,你可以使用帮助器,它返回所有文件内容作为字符串数组 - - (File.ReadAllLines())每行的字符串,然后使用LINQ来搜索子字符串。如果您使用的是.NET 4
或更新版本,则可以使用不会读取整个文件并且按读取的操作读取的新助手(File.ReadLines())。
.NET 2.0 - 3.5:
string pattern = "england";
IEnumerable<string> result = File.ReadAllLines()
.Where(l => l.Contains(pattern));
.NET4 - 4.5:
string pattern = "england";
IEnumerable<string> result = File.ReadLines()
.Where(l => l.Contains(pattern));
,如果你只需要而不是Where(l => l.Contains(pattern))
MSDN第一行使用.FirstOrDefault(l => l.Contains(pattern))
:
ReadLines和ReadAllLines方法的区别如下:当您使用 ReadLines时,可以在返回整个集合之前开始枚举字符串集合 ;当您使用ReadAllLines时,必须等待返回 数组之前返回整个字符串数组。因此,当您使用非常大的文件时,ReadLines可以更高效。
来源
2013-02-22 11:40:38
sll
由于寻找匹配对于解决方案,这里面临的一个挑战是在“Console.Writeline();”中写入的内容这样我就可以在控制台上找到与所需字符串匹配的所有行。 – 2013-02-23 18:03:00
那么写入控制台有什么挑战? – sll 2013-03-05 16:58:38