如何使用计时器监控文件大小的变化? [英] 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;
}
我的问题是如何检查 Tick 事件中的文件大小变化?当没有更多变化时,停止计时器.
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.
尝试使用 FileSystemWather:
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;
}
这是有效的,但我如何检查最后一次大小更改我的意思是如何在 5 或 10 秒后再次检查它以查看是否有另一个更改,如果没有则停止事件?
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.
推荐答案
首先,如果你没有充分的理由——不要使用定时器.在大多数情况下,这是一种不好的做法.考虑使用 FileSystemWatcher 代替.
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.
关于文件大小 - 为此使用 FileInfo 类.
Regarding the file size - use FileInfo class for that.
这篇关于如何使用计时器监控文件大小的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!