How to: Read Text from a File

2017-3-302 min to readContributors

In this article

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.

Example

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.

using System;
using System.IO;
class Test
{
public static void Main()
{
try
{ // Open the text file using a stream reader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
// Read the stream to a string, and write the string to the console.
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}

Imports System
Imports System.IO
Class Test
Public Shared Sub Main()
Try
' 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()
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

Example

The second example shows an asynchronous read operation within a Windows Presentation Foundation (WPF) application.