How do I read data from a text file?

Category: System.IO, viewed: 3K time(s).
using System;
using System.IO;

namespace Kodecsharp.Example.System.IO
{
    public class ReadTextFile
    {
        public static void Main(string[] args)
        {
            //
            // Open a text file using TextReader / StreamReader
            //
            TextReader reader = new StreamReader(@"C:\employee.txt");
            try
            {
                //
                // Read each line from the text file
                //
                string line = "";
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine("Line: " + line);
                }
            }
            finally
            {
                reader.Close();
            }

            reader = new StreamReader(@"C:\employee.txt");
            try
            {
                //
                // We can also use the ReadToEnd method to read the data from the 
                // text file in one go.
                //
                Console.WriteLine(reader.ReadToEnd());
            }
            finally
            {
                reader.Close();
            }

            Console.ReadLine();
        }
    }
}
Powered by Disqus