C#.NET 逐行讀取TXT文本

C#.NET 逐行讀取TXT文本

using System;  
using System.IO;  
  
class Program  
{  
    static void Main()  
    {  
        string filePath = @"C:\path\to\your\file.txt"; // 替換爲你的TXT文件路徑  
        try  
        {  
            // 創建一個StreamReader對象來讀取文件  
            using (StreamReader sr = new StreamReader(filePath))  
            {  
                string line;  
                // 逐行讀取文件,直到讀取完畢  
                while ((line = sr.ReadLine()) != null)  
                {  
                    // 在這裏處理每一行,例如打印到控制檯  
                    Console.WriteLine(line);  
                }  
            }  
        }  
        catch (Exception e)  
        {  
            // 處理可能出現的異常,例如文件不存在或沒有讀取權限等  
            Console.WriteLine("The file could not be read:");  
            Console.WriteLine(e.Message);  
        }  
    }  
}

11

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章