Wednesday, May 22, 2013

read last line from text file

use filestream to get last line from big text file

using System;
using System.IO;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string[] files = Directory.GetFiles("d:\\", "*.txt");
        foreach (string file in files)
        {
            string lastLine = Util.ReadLastLine(file);
            Console.WriteLine("File [{0}] has next last line:\n\t - \"{1}\"", file, lastLine);
        }
        Console.ReadKey();
    }
}
class Util
{
    public static string ReadLastLine(string fileName)
    {
        string lastLine = null;
        int buffsize = 1000; // Should be set to regular Line Size * 2-3

        if (!File.Exists(fileName))
            return lastLine;

        using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
        {
            if (fs.Length == 0)
                return lastLine;

            // create buffer
            buffsize = (int)Math.Min(buffsize, fs.Length);
            byte[] buffer = new byte[buffsize]; 

            // Read last 1000 bytes from the end
            fs.Seek(-buffsize, SeekOrigin.End);
            fs.Read(buffer, 0, buffer.Length);
            // Convert to ASCII string
            string strBuffer = Encoding.ASCII.GetString(buffer, 0, buffer.Length);

            // get the lines
            string[] strArr = strBuffer.Split('\n');
            // get last line
            lastLine = strArr[strArr.Length - 1];
        }

        return lastLine;
    }
}

No comments:

Post a Comment