How do I read data from a text file?

Category: System.IO, viewed: 953 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();
        }
    }
}
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Network Sites

Statistics

Locations of visitors to this page