title | description | ms.date | ms.custom | dev_langs | helpviewer_keywords | ms.assetid | |||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Read text from a file |
In this article, see examples of how to read text synchronously or asynchronously from a text file, using the StreamReader class in .NET for desktop apps. |
05/09/2024 |
devdivchpfy22 |
|
|
ed180baa-dfc6-4c69-a725-46e87edafb27 |
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.
Note
These code examples don't apply to Universal Windows (UWP) apps because the Windows runtime provides different stream types for reading and writing to files. For more information, see UWP work with 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.
-
Create a text file named TestFile.txt in the same folder as the app.
Add some content to the text file. The examples in this article write the content of the text file to the console.
The following example shows a synchronous read operation within a console app. The file contents are read and stored in a string variable, which is then written to the console.
- Create a xref:System.IO.StreamReader instance.
- Call the xref:System.IO.StreamReader.ReadToEnd?displayProperty=nameWithType method and assign the result to a string.
- Write the output to the console.
:::code language="csharp" source="snippets/how-to-read-text-from-a-file/csharp/Program.cs" id="sync"::: :::code language="vb" source="snippets/how-to-read-text-from-a-file/vb/Program.vb" id="sync":::
The following example shows an asynchronous read operation within a console app. The file contents are read and stored in a string variable, which is then written to the console.
- Create a xref:System.IO.StreamReader instance.
- Await the xref:System.IO.StreamReader.ReadToEndAsync?displayProperty=nameWithType method and assign the result to a string.
- Write the output to the console.
:::code language="csharp" source="snippets/how-to-read-text-from-a-file/csharp/Program.cs" id="async"::: :::code language="vb" source="snippets/how-to-read-text-from-a-file/vb/Program.vb" id="async":::
- Common I/O Tasks.
- Asynchronous file I/O.
- How to: Write text to a file.
- xref:System.IO.StreamReader
- xref:System.IO.File.OpenText%2A?displayProperty=nameWithType
- xref:System.IO.StreamReader.ReadLine%2A?displayProperty=nameWithType