逐個讀取檔案中所有行的 C# 程式


使用 ReadAllLines() 方法逐個讀取檔案中所有行。

假設有一個檔案“new.txt”,其中包含以下行。

One
Two
Three

首先,設定要讀取的檔案的路徑。

String myPath = "new.txt";

現在將其新增到一個字串陣列中,逐個獲取行。

String[] fLine = File.ReadAllLines(myPath);

假設你需要獲取第一行。為此。

fLine[0]

以下是逐個讀取檔案中行的完整示例。

示例

using System;
using System.IO;
public class Demo {
   public static void Main() {
      String myPath = "new.txt";
      String[] fLine;
      // array of lines in a file
      fLine = File.ReadAllLines(myPath);
      // read lines of a file
      Console.WriteLine("Line 1: "+fLine[0]);
      Console.WriteLine("Line 2: "+fLine[1]);
      Console.WriteLine("Line 3: "+fLine[2]);
      Console.WriteLine("Line 4 "+fLine[3]);
   }
}

輸出

Line1: One
Line2: Two
Line3: Three
Line4: Four

更新於: 2020 年 6 月 23 日

259 次瀏覽

啟動您的職業生涯

透過完成課程來獲得認證

開始
廣告