If I'm reading a text file in shared access mode and another process truncates it, what is the easiest way to detect that? (I'm excluding the obvious choice of refreshing a FileInfo object periodically to check its size) Is there some convenient way to capture an event? (Filewatcher?)
There is, It's called FileSystemWatcher.
If you are developing a windows forms application, you can drag-and-drop it from the toolbox.
Here's some usage example:
private void myForm_Load(object sender, EventArgs e)
{
var fileWatcher = new System.IO.FileSystemWatcher();
// Monitor changes to PNG files in C:\temp and subdirectories
fileWatcher.Path = @"C:\temp";
fileWatcher.IncludeSubdirectories = true;
fileWatcher.Filter = @"*.png";
// Attach event handlers to handle each file system events
fileWatcher.Changed += fileChanged;
fileWatcher.Created += fileCreated;
fileWatcher.Renamed += fileRenamed;
// Start monitoring!
fileWatcher.EnableRaisingEvents = true;
}
void fileRenamed(object sender, System.IO.FileSystemEventArgs e)
{
// a file has been renamed!
}
void fileCreated(object sender, System.IO.FileSystemEventArgs e)
{
// a file has been created!
}
void fileChanged(object sender, System.IO.FileSystemEventArgs e)
{
// a file is modified!
}
It's in System.IO and System.dll so you should be able to use it in most type of projects.
Just something to chew on; it may not apply to your situation:
chakrit's solution is correct for what you asked for, but I have to ask -- why are you reading a file while another process truncates it?
In particular, if you don't have some synchronization, reading/writing files concurrently is not particularly safe, and you may find you have other mysterious problems.
FSW cannot work reliably, it is asynchronous. Assuming you don't get an exception, StreamReader.ReadLine() will return null when the file got truncated. Then check if the size changed. Beware of the unavoidable race condition, you'll need to verify assumptions about timing.