Read a text file with C#

by Ben28. May 2012 20:18

This code will open a text file and read a line at the time displaying it in the console window until it reaches the end of the file.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            // Create an instance of StreamReader to read from a file.
            // The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
                String line;
                // Read and display lines from the file until the end of
                // the file is reached.
                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception ex)
        {
            // Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(ex.Message);
        }
    }
}

Reference MSDN

Tags: , ,

c#

Comments (2) -

GrantU
GrantU
6/11/2012 2:28:48 AM #

Enlightening. This has highlighted facets I have overlooked until now and I am grateful for your fresh insight!

CHARLES
CHARLES
6/14/2012 11:31:39 PM #

this is a great time saver, thank you very much $

Add comment

biuquote
  • Comment
  • Preview
Loading

RecentPosts