About Me

Wednesday, October 12, 2011

How to read a content of the text file in C#

While reading the book of Andrew Troelsen "C# 2010" I was very surprised when found really easy way how to read the content of the file.
What I always used to do when facing with the issue to read the content of the file is to use a filestream, read data to the bytes array and then convert it into text:
                
private static string ReadFile()
{
    FileInfo fileToRead = new FileInfo("SomeTextFile.txt");

    using (FileStream stream = fileToRead.OpenRead())
    {
        byte[] content = new byte[stream.Length];
        stream.Read(content, 0, content.Length);
        return Encoding.ASCII.GetString(content);
    }
}

private static string ReadFile2()
{
    FileInfo fileToRead = new FileInfo("SomeTextFile.txt");

    using (StreamReader stream = fileToRead.OpenText())
    {
        return stream.ReadToEnd();
    }
}
As you may see, the second method is much shorter then the first one. However, the code may be even more short:
                
private static string ReadFile3()
{
    return System.IO.File.ReadAllText("SomeTextFile.txt");
}
Look at the System.IO.File class! How many wonderful things it has inside that can make your code shorter and life easier!
 Below is few methods that will be very useful:

  • File.ReadAllLines("SomeTextFile.txt") - Opens the file read all lines and return you an array of lines instead of just a string
  • File.WriteAllLines("SomeTextFile.txt", new [] {"Line1", "Line2"}) - Opens a file and saves array of lines into it
  • File.WriteAllText("SomeTextFile.txt", "Line1\r\nLine2") - Opens a file and  writes a string into it.
There are much more.

The main benefit i see is that you should not care any more about closing the file after reading, handle streams and so on. Really, methods for lazy people! 
However, I still think its useful because can save your time for more important and interesting things!