Search code examples
c#fileshare

Read last line in open file


I'm fairly new all this, but I feel like I'm pretty close to making this work, I just need a little help! I want to create a DLL which can read and return the last line in a file that is open in another application. This is what my code looks like, I just don't know what to put in the while statement.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace SharedAccess
{
    public class ReadShare {
        static void Main(string path) {

            FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            StreamReader reader = new StreamReader(stream);

            while (!reader.EndOfStream)
            {
                //What goes here?
            }
        }
    }
}

Solution

  • To read last line,

    var lastLine = File.ReadLines("YourFileName").Last();
    

    If it's a large File

    public static String ReadLastLine(string path)
    {
        return ReadLastLine(path, Encoding.ASCII, "\n");
    }
    public static String ReadLastLine(string path, Encoding encoding, string newline)
    {
        int charsize = encoding.GetByteCount("\n");
        byte[] buffer = encoding.GetBytes(newline);
        using (FileStream stream = new FileStream(path, FileMode.Open))
        {
            long endpos = stream.Length / charsize;
            for (long pos = charsize; pos < endpos; pos += charsize)
            {
                stream.Seek(-pos, SeekOrigin.End);
                stream.Read(buffer, 0, buffer.Length);
                if (encoding.GetString(buffer) == newline)
                {
                    buffer = new byte[stream.Length - stream.Position];
                    stream.Read(buffer, 0, buffer.Length);
                    return encoding.GetString(buffer);
                }
            }
        }
        return null;
    }
    

    I refered here, How to read only last line of big text file