📜  file.readlines c# (1)

📅  最后修改于: 2023-12-03 15:00:45.095000             🧑  作者: Mango

使用 file.readlines() 函数在 C# 中读取文件内容

在 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.
参考文献