How to: Read Text from a File
The following examples show how to read text synchronously and asynchronously from a text file. In both examples, when you create the instance of the StreamReader class, you provide the relative or absolute path to the file. The following examples assume that the file named TestFile.txt is in the same folder as the application.
The first example shows a synchronous read operation within a console application.
Imports System Imports System.IO Class Test Public Shared Sub Main() Try Using sr As New StreamReader("TestFile.txt") Dim line As String line = sr.ReadToEnd() Console.WriteLine(line) End Using Catch e As Exception Console.WriteLine("The file could not be read:") Console.WriteLine(e.Message) End Try End Sub End Class
The second example shows an asynchronous read operation within a Windows Presentation Foundation (WPF) application.
Imports System.IO Class MainWindow Private Async Sub ReadFileButton_Click(sender As Object, e As RoutedEventArgs) Try Using sr As StreamReader = New StreamReader("TestFile.txt") Dim line = Await sr.ReadToEndAsync() ResultBlock.Text = line End Using Catch ResultBlock.Text = "Could not read the file" End Try End Sub End Class