Julie Lerman's DevLife

DevLife Part I [May 2005 - March 2007]

My Links

Blog Stats

News

A blog for DevSource.com.

This blog was originally part of the blogs.ziffdavis.com site from May 2005 through June 2007 when the blog was moved to the Movable Type blog engine and hosted at blog.devsource.com/devlife.
The original blog was eventually shut down and I was given the posts so that I could host them on my own site.


Archives

Snuck it right by me. File.ReadAllText, ReadAllLines, ReadAllBinary

One of the very sweet additions to the .NET Base Class Libraries in 2.0 that I have highlighted in presentations since early 2004 was the File.ReadAll method which would read the contents of a file and return a string. This feature is wonderful because prior to 2.0, a developer would need to learn all about streaming in order to do this simple task. Streams are not for the feint of heart. It just didn't seem fair. ReadAll's complement, File.WriteAll did just the opposite: wrote a string out to a text file. Simple.

I noticed in the past few days that these two have been expanded upon in the past months and have been replaced with three pairs of methods, Read/WriteAllText, Read/WriteAllLines and Read/WriteAllBinary.

These are really great - relatively small in the scope of all that is new in VS2005 but SO very useful and not to be missed!

ReadAllText Opens a text file. Reads all lines of the file into a string and then closes the file.
WriteAllText Creates a new file (or overwrites existing). Writes text into file. Closes the file.

ReadAllLines Opens a text file. Reads all lines into a string array (one element per line)
WriteAllLines Creates a new file (or overwrites existing). Writes each line from a string array. Closes the file.

The above methods also have an overload for assigning an encoding type.

ReadAllBytes Opens a binary file. Reads the contents into a byte array. Closes the file.
WriteAllBytes Opens a new file (or overwrites existing) . Writes the contents of a byte array into it. Closes the file.

If you need to do more complex functions with files, including the new ACL features (oooh aaaah) you can use the streaming methods still.

Here's a quick look at the difference between ReadAllText which creates one string and ReadAllLines which puts each line (paragraph) into a separate strings in an array. Note the fourth element.

ReadAllText

ReadAllLines

posted on Wednesday, September 07, 2005 9:27 AM