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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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();
        }
    }
}