This simple program imitates the unix "tail -f" utility on windows.
Source code and Demo
The submitted source code contains one main file: Tail.cs. This is the core of the tail program. This file is used in two wrappers - a GUI wrapper and a CUI wrapper. The two projects in the solution illustrate using Tail.cs in a windows form application and a console application.
.NET introduced the
FileSystemWatcher, which is the main component of this program. By configuring this component one can listen to file system changes.
I first check whether the file exists. If it does exist then I monitor any changes to the file thus:
fileSystemWatcher.Changed += new FileSystemEventHandler(TargetFile_Changed);
If it does not exist yet, then I wait until the file is created before watching for file change notifications:
fileSystemWatcher.Created += new FileSystemEventHandler(TargetFile_Created);
When a change is made to the file, the method below gets the notification
public void TargetFile_Changed(object source, FileSystemEventArgs e)
byte bytesRead = new byte[maxBytes];
FileStream fs = new FileStream(this.filename, FileMode.Open);
if (fs.Length > maxBytes)
this.previousSeekPosition = fs.Length - maxBytes;
this.previousSeekPosition = (int)fs.Seek(
int numBytes = fs.Read(bytesRead, 0, maxBytes);
this.previousSeekPosition += numBytes;
StringBuilder sb = new StringBuilder();
for (int i=0; i<numBytes; i++)
Within this, I ensure that the last characters are read in a large file which is longer than the number of characters that can be read. I then read the last set of characters starting from where we left off the previous time. The string of new characters is then sent to all listeners.
The sample programs listen to this notfication and then updates its user interface.
I have noticed an occasional exception saying that the target file is being accessed by another program. In the environment that I am working in, the target file is not always opened for writing, so I am able to get away with the above code for now. If it works, don't touch it uh. But you feel free to correct it and post changes.
- Added fix for file access exception. Thanks to Gary a.k.a garythom_work for this fix. (see thread below) - 17 Jan 2004