65.9K
CodeProject is changing. Read more.
Home

Tail.NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.30/5 (15 votes)

Jun 30, 2004

viewsIcon

116167

downloadIcon

1777

How to read changes from log files as they are written to. Similar to "tail" from UNIX.

Introduction

I've often remembered using the "tail" command in Linux and thought I could use the same thing in Windows. I've never been able to find a suitable Win32 replacement for the old utility so I had to roll my own. The only use I've found for the program is monitoring log files.

Using the code

There is very little code required to read the changes from a given file. The most notable piece from below is the way that the FileStream is created to read files that may be open by other processes. If you try to use the StreamReader's constructor to open a file in use by another process, you will get an exception. Of course, being able to read open files was crucial to this utility.

using ( StreamReader reader = new StreamReader(new FileStream(fileName, 
                     FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) )
{
    //start at the end of the file
    long lastMaxOffset = reader.BaseStream.Length;

    while ( true )
    {
        System.Threading.Thread.Sleep(100);

        //if the file size has not changed, idle
        if ( reader.BaseStream.Length == lastMaxOffset )
            continue;

        //seek to the last max offset
        reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);

        //read out of the file until the EOF
        string line = "";
        while ( (line = reader.ReadLine()) != null )
            Console.WriteLine(line);

        //update the last max offset
        lastMaxOffset = reader.BaseStream.Position;
    }
}