简体   繁体   中英

How to monitor file size changes using a timer?

private void MonitorFileForChanges()
{
    Timer timerFileMonitor = new Timer();
    timerFileMonitor.Interval = 10000;
    timerFileMonitor.Tick += timerFileMonitor_Tick;
    timerFileMonitor.Start();
}

void timerFileMonitor_Tick(object sender, EventArgs e)
{
    var directory = new DirectoryInfo(userVideosDirectory);
    var myFile = directory.GetFiles()
     .OrderByDescending(f => f.LastWriteTime)
     .First();
    long oldFileSize = 0;
}

My problem is how to check for the file size changes in the Tick event ? And when there is no more changes stop the timer.

Tried to use FileSystemWather:

private void WatchDirectory()
        {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = userVideosDirectory;
            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
            watcher.Filter = "*.mp4";
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.EnableRaisingEvents = true;
        }

        private void OnChanged(object source, FileSystemEventArgs e)
        {
            if (e.ChangeType == WatcherChangeTypes.Changed)
            {
                var info = new FileInfo(e.FullPath);
                var theSize = info.Length;
                label2.BeginInvoke((Action)(() =>
                {
                    label2.Text = theSize.ToString();
                }));
            }

            dirchanged = true;
        }

This is working but how do i check the last size change i mean how do i check it again after 5 or 10 seconds to see if there was another change and if not then stop the event ?

I mean there is no completed event like.

First of all, if you do not have a strong reason - do not use timer. It's a bad practice in most cases. Consider using FileSystemWatcher instead.

Regarding the file size - use FileInfo class for that.

You can use FileInfo.Length to get the size of the file in bytes. Something like:

FileInfo f = new FileInfo(pathOfTheFile);
long size = f.Length;
if (this.lastSize == size)
{
     timerFileMonitor.Stop();
}
else 
{
     this.lastSize = size;
}

You can stop the timer once the size of the file hasn't change since the last time. Just keep a field with the size and compare it.

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