HOW TO:一次一行讀取文字檔 (Visual C#)How to: Read a Text File One Line at a Time (Visual C#)

此範例會使用 StreamReader 類別的 ReadLine 方法,將文字檔的內容一次一行讀入字串中。This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. 每個文字行都會儲存到字串 line 中並顯示在畫面上。Each text line is stored into the string line and displayed on the screen.


int counter = 0;  
string line;  
// Read the file and display it line by line.  
System.IO.StreamReader file =   
    new System.IO.StreamReader(@"c:\test.txt");  
while((line = file.ReadLine()) != null)  
System.Console.WriteLine("There were {0} lines.", counter);  
// Suspend the screen.  

編譯程式碼Compiling the Code

將程式碼複製並貼到主控台應用程式的 Main 方法中。Copy the code and paste it into the Main method of a console application.

以實際檔案名稱取代 "c:\test.txt"Replace "c:\test.txt" with the actual file name.

穩固程式設計Robust Programming

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

  • 檔案可能不存在。The file may not exist.

.NET Framework 安全性.NET Framework Security

請勿根據檔案名稱來判斷檔案內容。Do not make decisions about the contents of the file based on the name of the file. 例如,myFile.cs 檔案可能不是 C# 原始程式檔。For example, the file myFile.cs may not be a C# source file.

另請參閱See also