Permalink
Fetching contributors…
Cannot retrieve contributors at this time
54 lines (47 sloc) 3.74 KB
title ms.custom ms.date ms.prod ms.reviewer ms.suite ms.technology ms.tgt_pltfrm ms.topic helpviewer_keywords ms.assetid caps.latest.revision author ms.author manager
How to: Read Text from a File
03/30/2017
.net
dotnet-standard
article
streams, reading text from files
reading text files
reading data, text files
data streams, reading text from files
I/O [.NET Framework], reading text from files
ed180baa-dfc6-4c69-a725-46e87edafb27
23
mairaw
mairaw
wpickett

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 xref:System.IO.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.

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.

[!code-csharpConceptual.BasicIO.TextFiles#3] [!code-vbConceptual.BasicIO.TextFiles#3]

Example

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

[!code-csharpConceptual.BasicIO.TextFiles#6] [!code-vbConceptual.BasicIO.TextFiles#6]

See Also

xref:System.IO.StreamReader
xref:System.IO.File.OpenText%2A?displayProperty=nameWithType
xref:System.IO.StreamReader.ReadLine%2A?displayProperty=nameWithType
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