如何:读取文本文件中的内容(C# 编程指南)

此示例读取文本文件的内容以使用 System.IO.File 选件类的静态方法 ReadAllTextReadAllLines

有关使用 StreamReader 的示例,请参见如何:一次一行地读取文本文件 (Visual C#)

注意
本示例的文件在主题 如何:写入文本文件(C# 编程指南)创建。
class ReadFromFile
{
    static void Main()
    {
        // The files used in this example are created in the topic
        // How to: Write to a Text File. You can change the path and
        // file name to substitute text 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. Variable text is a string.
        System.Console.WriteLine("Contents of WriteText.txt = {0}", text);

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

        // Display the file contents by using a foreach loop.
        System.Console.WriteLine("Contents of WriteLines2.txt = ");
        foreach (string line in lines)
        {
            // Use a tab to indent each line of the file.
            Console.WriteLine("\t" + line);
        }

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

编译代码

将代码复制并粘贴到 C# 控制台应用程序。

如果不使用从 如何:写入文本文件(C# 编程指南)的文本文件,请替换为您计算机上的参数。ReadAllTextReadAllLines 使用适当的路径和文件名。

可靠编程

以下情况可能会导致异常:

  • 文件不在指定的位置存在或不存在。检查路径和文件名的拼写。

.NET Framework 安全性

不要依赖文件名来确定文件的内容。例如,文件 myFile.cs 可能不是 C# 源文件。

请参阅

System.IO

C# 编程指南

文件系统和注册表(C# 编程指南)