C# 程序逐行读取文件中的所有行

csharpprogrammingserver side programming更新于 2025/9/14 13:03:00

使用 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;
      // 文件中行的数组
      fLine = File.ReadAllLines(myPath);
      // 读取文件中的行
      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

相关文章