The OpenText method opens an
existing UTF-8 encoded text file for reading. The OpenText method takes a file
name as a parameter and returns a StreamReader object.
StreamReader
reader = File.OpenText(fileName);
Once we have a StreamReader object, we can use its Read or ReadLine methods to
read the contents. The ReadLine method reads one line at a time. The following
code snippet loops through the entire content of a SteamReader and reads and
prints one line at a time.
while
((s = reader.ReadLine()) != null)
{
Console.WriteLine(s);
}
The following lists the
complete code sample.
string
fileName = @"C:\Temp\MaheshTX.txt";
try
{
using (StreamReader reader =
File.OpenText(fileName))
{
string s = "";
while ((s = reader.ReadLine()) !=
null)
{
Console.WriteLine(s);
}
}
}
catch
(Exception Ex)
{
Console.WriteLine(Ex.ToString());
}