从文件末尾开始读取,类似于tail [英] Read from a file starting at the end, similar to tail

查看:21
本文介绍了从文件末尾开始读取,类似于tail的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在原生 C# 中,如何从文件末尾读取?

In native C#, how can I read from the end of a file?

这是相关的,因为我需要读取一个日志文件,读取 10k,读取最后 3 行没有意义.

This is pertinent because I need to read a log file, and it doesn't make sense to read 10k, to read the last 3 lines.

推荐答案

读取最后 1024 个字节:

To read the last 1024 bytes:

using (var reader = new StreamReader("foo.txt"))
{
    if (reader.BaseStream.Length > 1024)
    {
        reader.BaseStream.Seek(-1024, SeekOrigin.End);
    }
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

这篇关于从文件末尾开始读取,类似于tail的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆