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;
//文件中的行数组
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