How to detect a truncated file in C #

If I am reading a text file in shared mode and another process is truncating it, what is the easiest way to detect this? (I rule out the obvious choice of updating the FileInfo object periodically to check its size.) Is there a convenient way to capture the event? (FileWatcher?)

0


source to share


3 answers


There is It called FileSystemWatcher .

If you are developing a Windows Forms Application, you can drag and drop it from the toolbar.

Here's a 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 can use it in most types of projects.

+3


source


FSW cannot run reliably, it is asynchronous. Assuming you don't get an exception, StreamReader.ReadLine () will return null when the file is truncated. Then check if the size has changed. Beware of the inevitable race condition, you will need to check the timing assumptions.



+3


source


Just chew something; it may not apply to your situation:

The chakrit solution is correct for what you asked, but I have to ask - why are you reading the file and another process is truncating it?

In particular, if you are out of sync, it is not safe to read and write files at the same time, and you may find that you have other cryptic problems.

0


source







All Articles