Export (0) Print
Expand All
15 out of 28 rated this helpful - Rate this topic

How to: Read Text from a File

The following examples show how to read text synchronously and asynchronously from a text file. 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.

The first example shows a synchronous read operation within a console application.

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            using (StreamReader sr = new StreamReader("TestFile.txt"))
            {
                String line = sr.ReadToEnd();
                Console.WriteLine(line);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

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";
            }
        }
    }
}
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.