-
Notifications
You must be signed in to change notification settings - Fork 39
/
FileMonitor.cs
76 lines (59 loc) · 2.21 KB
/
FileMonitor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
namespace MEditor
{
public class FileMonitor
{
private int TimeoutMillis = 2000;
System.IO.FileSystemWatcher fsw = new System.IO.FileSystemWatcher();
System.Threading.Timer m_timer = null;
List<String> files = new List<string>();
FileSystemEventHandler fswHandler = null;
public FileMonitor(FileSystemEventHandler watchHandler)
{
m_timer = new System.Threading.Timer(new TimerCallback(OnTimer), null, Timeout.Infinite, Timeout.Infinite);
fswHandler = watchHandler;
}
public FileMonitor(FileSystemEventHandler watchHandler, int timerInterval)
{
m_timer = new System.Threading.Timer(new TimerCallback(OnTimer), null, Timeout.Infinite, Timeout.Infinite);
TimeoutMillis = timerInterval;
fswHandler = watchHandler;
}
public void Add(string dir,string filter)
{
System.IO.FileSystemWatcher fsw = new System.IO.FileSystemWatcher(dir, filter);
fsw.NotifyFilter = System.IO.NotifyFilters.LastWrite;
fsw.Changed += new FileSystemEventHandler(OnFileChanged);
fsw.EnableRaisingEvents = true;
}
public void OnFileChanged(object sender, FileSystemEventArgs e)
{
//MessageBox.Show("Created", "Create triggered");
Mutex mutex = new Mutex(false, "FSW");
mutex.WaitOne();
if (!files.Contains(e.FullPath))
{
files.Add(e.FullPath);
}
mutex.ReleaseMutex();
m_timer.Change(TimeoutMillis, Timeout.Infinite);
}
private void OnTimer(object state)
{
List<String> backup = new List<string>();
Mutex mutex = new Mutex(false, "FSW");
mutex.WaitOne();
backup.AddRange(files);
files.Clear();
mutex.ReleaseMutex();
foreach (string file in backup)
{
fswHandler(this, new FileSystemEventArgs(WatcherChangeTypes.Changed, string.Empty, file));
}
}
}
}