.Net Framework 4.0: System.IO.File supports now IEnumerable
.Net Framework 4.0 adds also some new and cool features to file system objects. File class has now ReadLines() methods that returns IEnumerable<string>. WriteAllLines() methods has two overload methods that accept IEnumerable<string> instead of strings array that was also supported in previous versions of .Net Framework. This posting introduces ReadLines() and WriteAllLines() methods and gives you some ideas how to use these methods in your applications.
Querying file contents
My first example shows how to use ReadLines() to query file contents using LINQ. I have text file called lorem-ipsum.txt with some paragraphs with famous lorem ipsum text. You can generate your own text on www.lipsum.com. I use LINQ query to get all lines from this file that contain word ipsum.
static void Main(string[] args)
{
var lines = File.ReadLines("lorem-ipsum.txt");
var ipsumQuery = from l in lines
where l.ToLower().Contains("ipsum")
select l;
foreach (var ipsumLine in ipsumQuery)
{
Console.WriteLine(ipsumLine);
}
Console.ReadLine();
}
Even if you don’t use LINQ you can still consider using ReadLines() method – it doesn’t load all the contents from file to memory like ReadAllLines() does. When you are working with large files then ReadLines() is extremely useful method for you.
Writing query contents to file
My second example shows you how to write contents of IEnumerable<string> to file. ReadAllLines() method of File class has now two new overloads that accept IEnumerable<string>. To get example done with less effort we will use previous example and instead of printing lines to screen we will output them to separate file.
static void Main(string[] args)
{
var lines = File.ReadLines("lorem-ipsum.txt");
var ipsumQuery = from l in lines
where l.ToLower().Contains("ipsum")
select l;
File.WriteAllLines("only-ipsum.txt", ipsumQuery);
Console.ReadLine();
}
Although this example is not something markable or revolutionary it illustrates you how to query one file and output results to another file. Of course, you can use instead of file query everything else that implements IEnumerable<string> interface.
There is also AppendAllLines() method that appends lines to file instead of overwriting the file like WriteAllLines() does.
In my opinion these features are very good ones and you can use these methods in all of your applications where you need to read and query or query something and write results to files.
This is a nice feature to have.