读取文本文件时,应根据文件大小和内存限制选择方法:小文件用 readalltext 一次性加载为字符串,大文件用 readlines 逐行惰性读取以节省内存。避免使用 readalllines,因为它会将所有行加载到内存数组中,容易引发 outofmemoryexception。

ReadAllText 的适用场景与行为
ReadAllText 适用于小文件,它一次性读取全部内容并返回一个字符串。该方法内部会打开文件流,读取直到末尾,然后关闭流。如果文件很大,会导致内存占用过高。

using System;
using System.IO;
class Program
{
static void Main()
{
string path = "small_file.txt";
// 假设 small_file.txt 内容很小,例如几KB
string content = File.ReadAllText(path);
Console.WriteLine(content.Length); // 输出字符数
Console.WriteLine(content.GetType().Name); // 输出 String
}
}
预期结果:
1. content 变量包含文件全部文本。
2. Console.WriteLine(content.Length) 输出文件的字符总数。
3. Console.WriteLine(content.GetType().Name) 输出 String。
ReadLines 的适用场景与行为
ReadLines 适用于大文件,它返回一个 IEnumerable<string></string>,采用惰性求值(Lazy Evaluation),即每次迭代时才读取一行。这允许处理超出内存容量的大文件,因为不会一次性加载所有内容。

using System;
using System.IO;
class Program
{
static void Main()
{
string path = "large_file.txt";
// 假设 large_file.txt 内容很大,例如几百MB
int lineCount = 0;
foreach (string line in File.ReadLines(path))
{
lineCount++;
if (lineCount == 1)
{
Console.WriteLine(line); // 打印第一行
}
}
Console.WriteLine(lineCount); // 输出总行数
}
}
预期结果:
1. foreach 循环逐行读取文件,内存占用低。
2. Console.WriteLine(line) 仅打印第一行内容。
3. Console.WriteLine(lineCount) 输出文件的总行数。
4. 即使文件很大,也不会抛出 OutOfMemoryException。
基于 ReadLines 处理空行的具体行为
当使用 ReadLines 读取包含空行的文件时,它会返回空字符串 "" 作为该行元素,而不是跳过或忽略。开发者需要在处理逻辑中显式检查空行,以避免错误。
using System;
using System.IO;
class Program
{
static void Main()
{
string path = "file_with_empty_lines.txt";
// 假设文件内容为: "Line1\n\nLine3"
foreach (string line in File.ReadLines(path))
{
if (string.IsNullOrEmpty(line))
{
Console.WriteLine("Empty Line Detected");
}
else
{
Console.WriteLine(line);
}
}
}
}
预期结果:
1. 输出 Line1。
2. 输出 Empty Line Detected。
3. 输出 Line3。
4. ReadLines 将空行视为有效行,其值为空字符串。


















