简体   繁体   中英

Monitor a file for changes

I have been searching the web for good ideas on creating an application. service, or vb script that will constantly monitor a file for changes. However, I want it to alert me when there are NO changes. The file I am monitoring is a log created by a very important application. If that file stops growing then that means there is something wrong with the application and it has stopped writing to the log file.

Does anyone have any ideas? I have played around with the FileSystemWatcher class in C# but I don't know if there is a way to use to alert when a file does not change since all of the events look at changes.

Thank you.

Just use a timer that fires on an interval that that file should be updated in.

Check the file size ( FileInfo.Length ) and if it is the same as the last time the timer fired, it is not growing.

In this case you don't need a watcher, you could use a timer. Every few minutes (or whatever fits your needs), check the file size. Store the last size somewhere. The next time you check it, compare the previous value to the current one. If they are the same then the file has not changed and you can issue your alert.

A file doesn't change most of the time. You need to define a time period beyond which the logging process is considered to have stopped. Start a timer that (when it completes) will signal that logging has stopped. Reset the timer every time a change event rolls in.

You can use the FileSytemWatcher class:
http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx

update: well, it pays to read the question through to the end... You can set a Timer ( ref ) for the duration of inactivity you want to be alerted of and reset the timer in FileSystemWatcher events.

I suggest you to combine all answers you already got.

Use FileSytemWatcher class to watch for changes and use a timer to wait for some period of time since last change .

The simplest solution will look like ManualResetEvent and DateTime variables (don't forget memory barriers) and a background thread.

So, you'll have a something like this:

DateTime _lastChangeTime;
ManualResetEvent _exitEvent; // set this event to exit thread.

private void Watcher_Change(...)
{
    _lastChangeTime = DateTime.UtcNow;
    Thread.MemoryBarrier();
}


private void ThreadProc()
{
    while (_exitEvent.Wait(1000)) // every second
    {
        Thread.MemoryBarrier();

        if (DateTime.UtcNow.Subtract(lastChangeTime) > [some reasonable time])
        {
            // shit happens...
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM