How to: Read Text from a File

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. 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.

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);
        }
    }
}

Example

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

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

namespace WpfApplication
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void ReadFileButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                using (StreamReader sr = new StreamReader("TestFile.txt"))
                {
                    String line = await sr.ReadToEndAsync();
                    ResultBlock.Text = line;
                }
            }
            catch (Exception ex)
            {
                ResultBlock.Text = "Could not read the file";
            }
        }
    }
}
Show:
© 2016 Microsoft