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.
PrerequisitesCreate 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.
try
{
// Open the text file using a stream reader.
using StreamReader reader = new("TestFile.txt");
// Read the stream as a string.
string text = reader.ReadToEnd();
// Write the text to the console.
Console.WriteLine(text);
}
catch (IOException e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Try
' Open the text file using a stream reader.
Using reader As New StreamReader("TestFile.txt")
' Read the stream as a string.
Dim text As String = reader.ReadToEnd()
' Write the text to the console.
Console.WriteLine(text)
End Using
Catch ex As IOException
Console.WriteLine("The file could not be read:")
Console.WriteLine(ex.Message)
End Try
Read a file asynchronously
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.
try
{
// Open the text file using a stream reader.
using StreamReader reader = new("TestFile.txt");
// Read the stream as a string.
string text = await reader.ReadToEndAsync();
// Write the text to the console.
Console.WriteLine(text);
}
catch (IOException e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Try
' Open the text file using a stream reader.
Using reader As New StreamReader("TestFile.txt")
' Read the stream as a string.
Dim text As String = Await reader.ReadToEndAsync()
' Write the text to the console.
Console.WriteLine(text)
End Using
Catch ex As IOException
Console.WriteLine("The file could not be read:")
Console.WriteLine(ex.Message)
End Try
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4