Here is the code to read a text file from disk one line at a time into a string.  This code ensures the file exists and properly closes the file if an exception occurs.

using System;
using System.IO; 

namespace CSharp411
{
    class Program
    {
        static void Main( string[] args )
        {
            string filePath = @"c:temptest.txt";
            string line; 

            if (File.Exists( filePath ))
            {
                StreamReader file = null;
                try
                {
                    file = new StreamReader( filePath );
                    while ((line = file.ReadLine()) != null)
                    {
                        Console.WriteLine( line );
                    }
                }
                finally
                {
                    if (file != null)
                        file.Close();
                }
            } 

            Console.ReadLine();
        }
    }
}
Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot