How to: Read From a Text File (C# Programming Guide)

This example reads the contents of a text file by using the static methods on the System.IO.File class ReadAllText and ReadAllLines.

Note

The files that are used in this example were created in the topic How to: Write to a Text File (C# Programming Guide).

Example

class ReadFromFile
{
    static void Main()
    {
        // The files used here were created in the code example 
        // in How to: Write to a Text File. You can of course substitute 
        // other files of your own. 

        // Example #1 
        // Read the file as one string. 
        string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

        // Display the file contents to the console.
        System.Console.WriteLine("Contents of writeText.txt = {0}", text);

        // Example #2 
        // Read the file lines into a string array. 
        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");            

        System.Console.WriteLine("Contents of writeLines2.txt =:");
        foreach (string line in lines)
        {
            Console.WriteLine("\t" + line);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}

Compiling the Code

Copy the code and paste it into a console application.

Replace "c:\testdir" with the actual folder name.

Robust Programming

The following conditions may cause an exception:

  • The file may not exist.

Security

Do not rely on the name of a file to determine the contents of a file. For example, the file myFile.cs may not be a C# source file.

See Also

Concepts

C# Programming Guide

Reference

System.IO

Other Resources

File System and the Registry (C# Programming Guide)