-
Notifications
You must be signed in to change notification settings - Fork 0
/
DirectoryWatcher.cs
84 lines (70 loc) · 2.77 KB
/
DirectoryWatcher.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
77
78
79
80
81
82
83
84
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
internal class DirectoryWatcher : IHostedService
{
private IConfiguration _configuration;
private Unpacker _unpacker;
private ILogger _logger;
private FileSystemWatcher watcher;
public DirectoryWatcher(IConfiguration configuration, Unpacker unpacker, ILogger<DirectoryWatcher> logger)
{
_configuration = configuration;
_unpacker = unpacker;
_logger = logger;
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType != WatcherChangeTypes.Changed)
{
return;
}
_logger.LogInformation("Changed: {filePath}", e.FullPath);
}
private void OnCreated(object sender, FileSystemEventArgs e)
{
_logger.LogInformation("Created: {filePath}", e.FullPath);
}
private void OnDeleted(object sender, FileSystemEventArgs e) =>
_logger.LogInformation("Deleted: {filePath}", e.FullPath);
private void OnRenamed(object sender, RenamedEventArgs e)
{
_logger.LogInformation("Renamed: {oldFilePath} to {filePath}", e.OldFullPath,e.FullPath);
}
private void OnError(object sender, ErrorEventArgs e) =>
PrintException(e.GetException());
private void PrintException(Exception? ex)
{
if (ex != null) _logger.LogError(ex, "Message: {errorMessage}", ex.Message);
}
public Task StartAsync(CancellationToken cancellationToken)
{
var watchPath = _configuration["WatchDirectory"];
_logger.LogInformation("Setting up directory watch on {WatchPath}",watchPath);
watcher = new FileSystemWatcher(watchPath);
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
_logger.LogInformation("Setting up change listeners");
watcher.Changed += OnChanged;
watcher.Created += OnCreated;
watcher.Deleted += OnDeleted;
watcher.Renamed += OnRenamed;
watcher.Error += OnError;
watcher.Filter = "*.txt";
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Shutting down...");
watcher.Dispose();
return Task.CompletedTask;
}
}