根据项目需要,需要读取指定文本最后N行数据。 搜了一下网上的解决方案,全都是使用File.ReadAllLines,一次读到数组里,然后再用下标来截取。

但是我的文件可能有几万行数据,一次全加载,性能上存在问题。于是抽空写了一个读取函数

private string getCurrentFileLine(string filepath, int rownum)
{
    if (!File.Exists(filepath))
        return "文件未找到 file -> " + filepath;

    List<string> lstResult = null;
    List<string> lstCursor = new List<string>();
    StreamReader objSr = new StreamReader(filepath, Encoding.Default);
    while (!objSr.EndOfStream)
    {
        // 向游标内增加一行数据
        lstCursor.Add(objSr.ReadLine());
        // 判断是否超限
        if(rownum <= lstCursor.Count)
        {
            // 超限的话,替换容器
            lstResult = new List<string>(lstCursor);
            lstCursor.Clear();
        }
    }

    // 做替换处理
    if (lstResult == null || lstResult.Count == 0)
    {
        lstResult = new List<string>(lstCursor);
    }
    else
    {
        lstResult.RemoveRange(0, lstCursor.Count);
        lstResult.AddRange(lstCursor);
    }

    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.AppendLine("============ getLogFile begin ============");
    foreach (var item in lstResult)
    {
        sb.AppendLine(item);
    }
    sb.AppendLine("============ getDLLPath end ============");
    return sb.ToString();
}