C# winform如何读取文本文件的后N行??

2025-03-13 06:46:43
推荐回答(4个)
回答1:

  1. 读取整个文本文件到数组

  2. 取得数组长度(文本行数)

  3. 读取文本后N行(lineCount -N)

  4. 将读取的内容写入到字符串temp内,tem就是文本文件后N行的内容


String[] strFile = File.ReadAllLines(@"D:\123.txt");

String temp = "";

int lineCount = strFile.Length;

for (int i = (lineCount - 5); i < lineCount; i++)

{

    temp += strFile[i] + "\r\n";

}

回答2:

1楼的不是C#吧。
C#只有ReadLine()可以读行;你用循环取出来放到数组,想从哪开始不久简单了吗。
你可以先全部读出来,在分行取!
你也可以使用流的形式读取,根据换行的标记进行分组。(不知道seek能查不)

回答3:

public ArrayList ReadLastLine(string sFileName,int nLastLine)
{
//============ 1. 打开文件 ==============
StreamReader reader;
reader = new StreamReader(
(System.IO.Stream)File.OpenRead(sFileName), Encoding.Default);

//========== 2. 读取文件 =============
ArrayList arrLast = new ArrayList();
while (!reader.EndOfStream)
{
string sLine = reader.ReadLine();
if (arrLast.Count == nLastLine)
{
arrLast.Clear();
}
arrLast.Add(sLine);
}
reader.Close();
return arrLast;
}

回答4:

// 按行读取文件
var lines = File.ReadAllLines("文件路径", Encoding.Default);
// 跳过前面的总行数-N行
lines = lines.Skip(lines.Length - N).ToArray();

补充:
C# 3.5的语法,二楼不认识不要随便说。
请问LZ,有你见过百万行的文本文件么?这个数据量的肯定是存数据库的,没有人二到用TXT去存。
退一万步,真的要这么做,那就只能用FileStream按二进制的方式从后往前找换行符了——前提是总行数已知。