如何高效读取文本文件的指定行
使用 file.readlines() 配合 linq 的 elementat() 可以最简洁地获取指定行。该方法采用延迟执行机制,只逐行读取直到目标索引,不会一次性加载整个文件到内存,适合处理大文件。

在 .NET Framework 中如何实现兼容读取
对于不支持 File.ReadLines() 的旧版环境或需要更精细控制的场景,可以使用 StreamReader 手动遍历行。通过循环累加计数器并在匹配时返回结果,可以在找到目标后立即停止读取,同样避免全量加载。

当请求的行号超出文件实际行数时会发生什么
如果请求的行号大于文件的总行数,上述两种方法都会抛出异常。具体而言,ElementAt() 会抛出 ArgumentOutOfRangeException,而 StreamReader 的手动实现若未做边界检查也会因访问空引用或逻辑错误导致问题,因此在使用前需确保行号有效或捕获异常。
using System;
using System.IO;
using System.Linq;
class Program
{
static void Main()
{
string filePath = "example.txt";
int targetLineIndex = 5; // 0-based index, so this is the 6th line
try
{
// Method 1: Using File.ReadLines and LINQ
string lineFromReadLines = File.ReadLines(filePath)
.ElementAt(targetLineIndex);
Console.WriteLine($"Method 1 Result: {lineFromReadLines}");
}
catch (Exception ex)
{
Console.WriteLine($"Method 1 Error: {ex.Message}");
}
try
{
// Method 2: Using StreamReader
string lineFromReader = GetLineByStreamReader(filePath, targetLineIndex);
Console.WriteLine($"Method 2 Result: {lineFromReader}");
}
catch (Exception ex)
{
Console.WriteLine($"Method 2 Error: {ex.Message}");
}
// Test with out-of-bounds index
int outOfBoundsIndex = 1000;
try
{
string lineOutOfBounds = File.ReadLines(filePath)
.ElementAt(outOfBoundsIndex);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine($"Out of Bounds Error: {ex.GetType().Name}");
}
}
static string GetLineByStreamReader(string path, int index)
{
using (var reader = new StreamReader(path))
{
string line;
int current = 0;
while ((line = reader.ReadLine()) != null)
{
if (current == index)
{
return line;
}
current++;
}
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");
}
}
}
预期结果:对于包含至少6行的文件,前两个方法分别输出第6行的内容。当请求第1000行时,控制台将打印 “Out of Bounds Error: ArgumentOutOfRangeException”。











