如何:從文字檔讀取 (C# 程式設計手冊)How to: Read From a Text File (C# Programming Guide)

這個範例會使用 System.IO.File 類別中的靜態方法 ReadAllTextReadAllLines,來讀取文字檔的內容。This example reads the contents of a text file by using the static methods ReadAllText and ReadAllLines from the System.IO.File class.

如需使用 StreamReader 的範例,請參閱如何:一次一行讀取文字檔For an example that uses StreamReader, see How to: Read a Text File One Line at a Time.

注意

此範例中所用的檔案是在如何︰寫入文字檔主題中建立。The files that are used in this example are created in the topic How to: Write to a Text File.

範例Example

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

編譯程式碼Compiling the Code

將程式碼複製並貼到 C# 主控台應用程式中。Copy the code and paste it into a C# console application.

如果您不想使用如何︰寫入文字檔中的文字檔,請以您電腦上的適當路徑和檔案名稱取代 ReadAllTextReadAllLines 的引數。If you are not using the text files from How to: Write to a Text File, replace the argument to ReadAllText and ReadAllLines with the appropriate path and file name on your computer.

穩固程式設計Robust Programming

以下條件可能會造成例外狀況:The following conditions may cause an exception:

  • 檔案不存在或不在指定的位置。The file doesn't exist or doesn't exist at the specified location. 請檢查路徑和檔案名稱的拼字。Check the path and the spelling of the file name.

.NET Framework 安全性.NET Framework Security

請勿依賴檔案的名稱來判斷檔案的內容。Do not rely on the name of a file to determine the contents of the file. 例如,myFile.cs 檔案可能不是 C# 原始程式檔。For example, the file myFile.cs might not be a C# source file.

請參閱See Also

System.IO
C# 程式設計指南C# Programming Guide
檔案系統和登錄 (C# 程式設計指南)File System and the Registry (C# Programming Guide)