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

c#中如何读取文本文件的最后一行?
希望完整代码!
谢谢 darko2o8,分给你了,想了很多办法,这个方法确实不错

两种方法:

    一行一行读,读到文件尾,你就知道哪行是最好一行了。可以考虑使用System.IO.File.ReadAllLines()方法,返回值是字符串数组。 

    File.ReadAllLines 方法 (System.IO)

    https://msdn.microsoft.com/zh-cn/library/System.IO.File.ReadAllLines(v=vs.110).aspx

    从流的末尾一个字节一个字节往前读,读到换行符以后,再从这个位置读到文件结尾。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-06-18
读取文本中的每一行没问题吧。

申明一个变量保存当前读取的数据,当读取结束了,该变量就是最后一行的读取数据。
第2个回答  2009-10-17
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
*/
}本回答被提问者和网友采纳
第3个回答  2015-07-07
FileStream fs = new FileStream("1.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
Queue<long> last5pos = new Queue<long>();
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[i].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();
相似回答