c#中如何读取文本文件的最后一行?

[复制链接]
查看11 | 回复2 | 2015-8-3 07:58:35 | 显示全部楼层 |阅读模式
读取文本中的每一行没问题吧。申明一个变量保存当前读取的数据,当读取结束了,该变量就是最后一行的读取数据。
回复

使用道具 举报

千问 | 2015-8-3 07:58:35 | 显示全部楼层
using System.IO;
class Program
{
static void Main(string[] args)
{
string oldValue = string.Empty,newValue = string.Empty;
using (StreamReader read = new StreamReader(@"c:\\a.txt", true))
{
do
{
newValue = read.ReadLine();
oldValue = newValue != null ? newValue : oldValue;
} while (newValue != null);
}
Console.WriteLine(oldValue);//输出 ccccccccccc
}
/*
a.txt 文件内容:
aaaaaaaaaa
bbbbbbbbb
ccccccccccc
*/
}
回复

使用道具 举报

千问 | 2015-8-3 07:58:35 | 显示全部楼层
FileStream fs = new FileStream("1.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
Queue last5pos = new Queue();
last5pos.Enqueue(0);
fs.Seek(0, SeekOrigin.Begin);
long pos = 0;
while (!sr.EndOfStream)
{
char cur = (char)sr.Read();
pos ++;
if(cur == '\r')
{
char next = (char)sr.Peek();
if (next == '\n')
{
last5pos.Enqueue(pos);
if (last5pos.Count > 5)
last5pos.Dequeue();
}
}
}
sr.Close();
long[] poslist = last5pos.ToArray();
for(int i=0; i< poslist.Length; i++)
Console.WriteLine(poslist.ToString());
if(poslist[poslist.Length - 1] + 1 == fs.Length)
{
fs.Seek(poslist[poslist.Length -2] + 1, SeekOrigin.Begin);
byte[] buffer = new byte[poslist[poslist.Length - 1] - poslist[poslist.Length -2] - 1];
fs.Read(buffer, 0, buffer.Length);
Console.WriteLine(Encoding.Default.GetString(buffer));
}
else
{
fs.Seek(poslist[poslist.Length -1] + 1, SeekOrigin.Begin);
byte[] buffer = new byte[fs.Length - poslist[poslist.Length -1] - 1];
fs.Read(buffer, 0, buffer.Length);
Console.WriteLine(Encoding.Default.GetString(buffer));
}
fs.Close();
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行