Therefore, when you are working with very large files, ReadLines can be more efficient.
You can use the ReadLines method to do the following:
Perform LINQ to Objects queries on a file to obtain a filtered set of its lines.
Write the returned collection of lines to a file with the File.WriteAllLines(String,
IEnumerable<String>) method, or append them to an existing file with the
File.AppendAllLines(String, IEnumerable<String>) method.
Create an immediately populated instance of a collection that takes an IEnumerable<T>
collection of strings for its constructor, such as a IList<T> or a Queue<T>.
Examples:
foreach (string line in File.ReadLines(@"d:\data\episodes.txt"))
{
if (line.Contains("episode") & line.Contains("2006"))
{
Console.WriteLine(line);
}
}
The following example uses the ReadLines method in a LINQ query that enumerates all
directories for files that have a .txt extension, reads each line of the file,
and displays the line if it contains the string "Microsoft".
using System;
using System.IO;
using System.Linq;
class Program
{
static void Main(string[] args)
{
try
{
var files = from file in Directory.EnumerateFiles(@"c:\",
"*.txt", SearchOption.AllDirectories)
from line in File.ReadLines(file)
where line.Contains("Microsoft")
select new
{
File = file,
Line = line
};
foreach (var f in files)
{
Console.WriteLine("{0}\t{1}", f.File, f.Line);
}
Console.WriteLine("{0} files found.",
files.Count().ToString());
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
}
}