Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / tools

A C# implementation of the Tail -f command

3.73/5 (3 votes)
19 Dec 2010CPOL 21.7K  
Unless I'm misreading your code on CodePlex, it looks like your utility loads in the entire file every time it changes. That might be fine for tiny files, but it would be a huge performance hit for larger ones (a few megs, for example).Why not do it a bit more simply?using (FileStream str...
Unless I'm misreading your code on CodePlex, it looks like your utility loads in the entire file every time it changes. That might be fine for tiny files, but it would be a huge performance hit for larger ones (a few megs, for example).

Why not do it a bit more simply?
C#
using (FileStream str = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))

I just tested this with a quick console app... You can write to the file from outside without any problems. You can rename it, and the C# code will still function. You can TRY to delete it, but it won't actually disappear until the FileStream is closed (and subsequent attempts to operate on it will fail). For a rolling log situation, that seems to be acceptable.

With this method, you can just keep track of your position in the file, and watch for the stream length to become greater than your current position. You can still use a FileSystemWatcher to catch the rename event, close your stream, and wait for a new file with the original name.

The tool's visible functionality (Parameters, string matching, etc.) could still be very useful... Just need to tweak the internals.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)