Reading Text from a File

Imports System
Imports System.IO
Class Test
PublicSharedSub Main()
Try' Create an instance of StreamReader to read from a file.Dim sr As StreamReader = New StreamReader("TestFile.txt")
Dim line AsString' Read and display the lines from the file until the end ' of the file is reached.Do
line = sr.ReadLine()
Console.WriteLine(Line)
LoopUntil line IsNothing
sr.Close()
Catch E As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(E.Message)
EndTryEndSubEndClass
[C#]using System;
using System.IO;
class Test
{
publicstatic void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

The following code example reads an entire file and notifies you when the end of the file is detected.

This code creates a StreamReader that points to MyFile.txt through a call to File.OpenText. StreamReader.ReadLine returns each line as a string. When there are no more characters to read, a message is displayed to that effect, and the stream is closed.