📅  最后修改于: 2023-12-03 15:00:45.095000             🧑  作者: Mango
在 C# 中,可以使用 System.IO.File
类中的 ReadAllLines
方法读取文件的所有行内容。该方法返回一个字符串数组,其中数组的每个元素表示文件中的一行。
string[] lines = System.IO.File.ReadAllLines(@"C:\example.txt");
foreach (string line in lines) {
Console.WriteLine(line);
}
在上面的示例中,我们使用 System.IO.File
类的 ReadAllLines
方法来读取 C:\example.txt
文件中的所有行内容,并将其存储在名为 lines
的字符串数组中。然后,我们使用 foreach
循环遍历该数组,以逐行输出文件的内容到控制台。
在使用 ReadAllLines
方法时,需要注意以下几点:
System.IO.FileNotFoundException
异常;System.OutOfMemoryException
异常;System.IO.StreamReader
类。假设我们有以下文本内容保存在名为 example.txt
的文本文件中:
This is the first line.
This is the second line.
This is the third line.
现在,我们可以使用以下 C# 代码读取该文件的每一行内容:
using System;
class Program {
static void Main() {
string[] lines = System.IO.File.ReadAllLines(@"C:\example.txt");
foreach (string line in lines) {
Console.WriteLine(line);
}
}
}
输出结果将如下所示:
This is the first line.
This is the second line.
This is the third line.