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.

Note

These code examples do not apply to developing for Universal Windows (UWP) apps, because the Windows Runtime provides different stream types for reading and writing to files. For an example that shows how to read text from a file in a UWP 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.

Example: Synchronous read in a console app

The following example shows a synchronous read operation within a console app. This example opens the text file using a stream reader, copies the contents to a string, and outputs the string to the console.

Important

The example assumes that a file named TestFile.txt already exists in the same folder as the app.

using System;
using System.IO;

class Test
{
public static void Main()
{
try
{   // Open the text file using a stream reader.
{
// Read the stream to a string, and write the string to the console.
Console.WriteLine(line);
}
}
catch (IOException e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

Imports System.IO

Class Test
Public Shared Sub Main()
Try
' Open the file using a stream reader.
' Read the stream to a string and write the string to the console.
Console.WriteLine(line)
End Using
Catch e As IOException
Console.WriteLine("The file could not be read:")
Console.WriteLine(e.Message)
End Try
End Sub
End Class


Example: Asynchronous read in a WPF app

The following example shows an asynchronous read operation in a Windows Presentation Foundation (WPF) app.

Important

The example assumes that a file named TestFile.txt already exists in the same folder as the app.

using System;
using System.IO;
using System.Windows;

namespace TextFiles
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
{
ResultBlock.Text = line;
}
}
catch (FileNotFoundException ex)
{
ResultBlock.Text = ex.Message;
}
}
}
}

Imports System.IO
Imports System.Windows

''' <summary>
''' Interaction logic for MainWindow.xaml
''' </summary>

Partial Public Class MainWindow
Inherits Window
Public Sub New()
InitializeComponent()
End Sub

Private Async Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs)
Try