File.ReadAll() and File.WriteAll()

Posted Thursday, December 9, 2004 8:42 AM by C-Dog's .NET Tip of the Day
Ever wanted to open a file and store it in a string and not worry about having to deal with streams and all that crap?  Well now you can with File.ReadAll and File.WriteAll.  The ReadAll method will open a file, read the entire contents into a string, and then close the file.
 
// read the entire contents of the file into a string
string fileString = File.ReadAll("ReservationLabels_en-US.xml");
 
The WriteAll method crates a new file, writes the contents of the string to the file and then closes the file.  If the file already exists, it is overwritten.
 
// write the entire contents of the string into the file
File.WriteAll("ReservationLabels_en-US.xml", fileString);
 
If you need a little more control of the file, you can use the File.ReadAllLines() and File.WriteAllLines methods.  These methods do the same thing as the previous methods except that each line is stored as a different element in a string array.
 
// read entire file into an array of strings
string fileStringArray[] = File.ReadAllLines("ReservationLabels_en-US.xml");
 
If you are working with binary files, you can use the File.ReadAllBytes() and File.WriteAllBytes() methods to read the contents of the file into a byte array.
 
Although working with files has never been terribly difficult, this certainly makes dealing with files in these situations even easier.

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=217