How to: Read Text from a File


The following examples show how to read text synchronously and asynchronously from a text file using .NET for desktop apps. 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.

These code examples do not apply developing for Windows Store Apps because the Windows Runtime provides different streams types reading and writing to files. For an example that shows how to read text from a file within the context of a Windows Store app, see Quickstart: Reading and writing files. For examples that show how to convert between .NET Framework streams and Windows runtime streams see How to: Convert Between .NET Framework Streams and Windows Runtime Streams.

The first example shows a synchronous read operation within a console application. In this example, the text file is opened using a stream reader, the contents are copied to a string and string is output to the console.

Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
            ' Open the file using a stream reader.
            Using sr As New StreamReader("TestFile.txt")
                Dim line As String
                ' Read the stream to a string and write the string to the console.
                line = sr.ReadToEnd()
            End Using
        Catch e As Exception
            Console.WriteLine("The file could not be read:")
        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)
            Using sr As StreamReader = New StreamReader("TestFile.txt")
                Dim line = Await sr.ReadToEndAsync()
                ResultBlock.Text = line
            End Using
            ResultBlock.Text = "Could not read the file"
        End Try
    End Sub
End Class

Asynchronous File I/O
NIB: How to: Create a Directory Listing
Quickstart: Reading and writing files
How to: Convert Between .NET Framework Streams and Windows Runtime Streams
How to: Read and Write to a Newly Created Data File
How to: Open and Append to a Log File
How to: Write Text to a File
How to: Read Characters from a String
How to: Write Characters to a String
File and Stream I-O