/
FileSystemWatcher.cs
787 lines (693 loc) · 26.6 KB
/
FileSystemWatcher.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO.Enumeration;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
/// <devdoc>
/// Listens to the system directory change notifications and
/// raises events when a directory or file within a directory changes.
/// </devdoc>
public partial class FileSystemWatcher : Component, ISupportInitialize
{
// Filters collection
private readonly NormalizedFilterCollection _filters = new NormalizedFilterCollection();
// Directory being monitored
private string _directory;
// The watch filter for the API call.
private const NotifyFilters c_defaultNotifyFilters = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
private NotifyFilters _notifyFilters = c_defaultNotifyFilters;
// Flag to watch subtree of this directory
private bool _includeSubdirectories;
// Flag to note whether we are attached to the thread pool and responding to changes
private bool _enabled;
// Are we in init?
private bool _initializing;
// Buffer size
private uint _internalBufferSize = 8192;
// Used for synchronization
private bool _disposed;
// Event handlers
private FileSystemEventHandler? _onChangedHandler;
private FileSystemEventHandler? _onCreatedHandler;
private FileSystemEventHandler? _onDeletedHandler;
private RenamedEventHandler? _onRenamedHandler;
private ErrorEventHandler? _onErrorHandler;
private const int c_notifyFiltersValidMask = (int)(NotifyFilters.Attributes |
NotifyFilters.CreationTime |
NotifyFilters.DirectoryName |
NotifyFilters.FileName |
NotifyFilters.LastAccess |
NotifyFilters.LastWrite |
NotifyFilters.Security |
NotifyFilters.Size);
#if DEBUG
static FileSystemWatcher()
{
int s_notifyFiltersValidMask = 0;
foreach (int enumValue in Enum.GetValues<NotifyFilters>())
s_notifyFiltersValidMask |= enumValue;
Debug.Assert(c_notifyFiltersValidMask == s_notifyFiltersValidMask, "The NotifyFilters enum has changed. The c_notifyFiltersValidMask must be updated to reflect the values of the NotifyFilters enum.");
}
#endif
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class.
/// </devdoc>
public FileSystemWatcher()
{
_directory = string.Empty;
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class,
/// given the specified directory to monitor.
/// </devdoc>
public FileSystemWatcher(string path)
{
CheckPathValidity(path);
_directory = path;
}
/// <devdoc>
/// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class,
/// given the specified directory and type of files to monitor.
/// </devdoc>
public FileSystemWatcher(string path, string filter)
{
CheckPathValidity(path);
ArgumentNullException.ThrowIfNull(filter);
_directory = path;
Filter = filter;
}
/// <devdoc>
/// Gets or sets the type of changes to watch for.
/// </devdoc>
public NotifyFilters NotifyFilter
{
get
{
return _notifyFilters;
}
set
{
if (((int)value & ~c_notifyFiltersValidMask) != 0)
throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, nameof(value), (int)value, nameof(NotifyFilters)));
if (_notifyFilters != value)
{
_notifyFilters = value;
Restart();
}
}
}
public Collection<string> Filters => _filters;
/// <devdoc>
/// Gets or sets a value indicating whether the component is enabled.
/// </devdoc>
public bool EnableRaisingEvents
{
get
{
return _enabled;
}
set
{
if (_enabled == value)
{
return;
}
if (IsSuspended())
{
_enabled = value; // Alert the Component to start watching for events when EndInit is called.
}
else
{
if (value)
{
StartRaisingEventsIfNotDisposed(); // will set _enabled to true once successfully started
}
else
{
StopRaisingEvents(); // will set _enabled to false
}
}
}
}
/// <devdoc>
/// Gets or sets the filter string, used to determine what files are monitored in a directory.
/// </devdoc>
public string Filter
{
get
{
return Filters.Count == 0 ? "*" : Filters[0];
}
set
{
Filters.Clear();
Filters.Add(value);
}
}
/// <devdoc>
/// Gets or sets a value indicating whether subdirectories within the specified path should be monitored.
/// </devdoc>
public bool IncludeSubdirectories
{
get
{
return _includeSubdirectories;
}
set
{
if (_includeSubdirectories != value)
{
_includeSubdirectories = value;
Restart();
}
}
}
/// <devdoc>
/// Gets or sets the size of the internal buffer.
/// </devdoc>
public int InternalBufferSize
{
get
{
return (int)_internalBufferSize;
}
set
{
if (_internalBufferSize != value)
{
if (value < 4096)
{
_internalBufferSize = 4096;
}
else
{
_internalBufferSize = (uint)value;
}
Restart();
}
}
}
/// <summary>Allocates a buffer of the requested internal buffer size.</summary>
/// <returns>The allocated buffer.</returns>
private byte[] AllocateBuffer()
{
try
{
return new byte[_internalBufferSize];
}
catch (OutOfMemoryException)
{
throw new OutOfMemoryException(SR.Format(SR.BufferSizeTooLarge, _internalBufferSize));
}
}
/// <devdoc>
/// Gets or sets the path of the directory to watch.
/// </devdoc>
[Editor("System.Diagnostics.Design.FSWPathEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public string Path
{
get
{
return _directory;
}
set
{
value ??= string.Empty;
if (!string.Equals(_directory, value, PathInternal.StringComparison))
{
if (value.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidDirName, value), nameof(Path));
if (!Directory.Exists(value))
throw new ArgumentException(SR.Format(SR.InvalidDirName_NotExists, value), nameof(Path));
_directory = value;
Restart();
}
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is changed.
/// </devdoc>
public event FileSystemEventHandler? Changed
{
add
{
_onChangedHandler += value;
}
remove
{
_onChangedHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is created.
/// </devdoc>
public event FileSystemEventHandler? Created
{
add
{
_onCreatedHandler += value;
}
remove
{
_onCreatedHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is deleted.
/// </devdoc>
public event FileSystemEventHandler? Deleted
{
add
{
_onDeletedHandler += value;
}
remove
{
_onDeletedHandler -= value;
}
}
/// <devdoc>
/// Occurs when the internal buffer overflows.
/// </devdoc>
public event ErrorEventHandler? Error
{
add
{
_onErrorHandler += value;
}
remove
{
_onErrorHandler -= value;
}
}
/// <devdoc>
/// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/>
/// is renamed.
/// </devdoc>
public event RenamedEventHandler? Renamed
{
add
{
_onRenamedHandler += value;
}
remove
{
_onRenamedHandler -= value;
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
//Stop raising events cleans up managed and
//unmanaged resources.
StopRaisingEvents();
// Clean up managed resources
_onChangedHandler = null;
_onCreatedHandler = null;
_onDeletedHandler = null;
_onRenamedHandler = null;
_onErrorHandler = null;
}
else
{
FinalizeDispose();
}
}
finally
{
_disposed = true;
base.Dispose(disposing);
}
}
private static void CheckPathValidity(string path)
{
ArgumentNullException.ThrowIfNull(path);
// Early check for directory parameter so that an exception can be thrown as early as possible.
if (path.Length == 0)
throw new ArgumentException(SR.Format(SR.InvalidDirName, path), nameof(path));
if (!Directory.Exists(path))
throw new ArgumentException(SR.Format(SR.InvalidDirName_NotExists, path), nameof(path));
}
/// <summary>
/// Sees if the name given matches the name filter we have.
/// </summary>
private bool MatchPattern(ReadOnlySpan<char> relativePath)
{
ReadOnlySpan<char> name = IO.Path.GetFileName(relativePath);
if (name.Length == 0)
return false;
string[] filters = _filters.GetFilters();
if (filters.Length == 0)
return true;
foreach (string filter in filters)
{
if (FileSystemName.MatchesSimpleExpression(filter, name, ignoreCase: !PathInternal.IsCaseSensitive))
return true;
}
return false;
}
/// <summary>
/// Raises the event to each handler in the list.
/// </summary>
private void NotifyInternalBufferOverflowEvent()
{
if (_onErrorHandler != null)
{
OnError(new ErrorEventArgs(
new InternalBufferOverflowException(SR.Format(SR.FSW_BufferOverflow, _directory))));
}
}
/// <summary>
/// Raises the event to each handler in the list.
/// </summary>
private void NotifyRenameEventArgs(WatcherChangeTypes action, ReadOnlySpan<char> name, ReadOnlySpan<char> oldName)
{
// filter if there's no handler or neither new name or old name match a specified pattern
if (_onRenamedHandler != null &&
(MatchPattern(name) || MatchPattern(oldName)))
{
OnRenamed(new RenamedEventArgs(action, _directory, name.IsEmpty ? null : name.ToString(), oldName.IsEmpty ? null : oldName.ToString()));
}
}
private FileSystemEventHandler? GetHandler(WatcherChangeTypes changeType)
{
switch (changeType)
{
case WatcherChangeTypes.Created:
return _onCreatedHandler;
case WatcherChangeTypes.Deleted:
return _onDeletedHandler;
case WatcherChangeTypes.Changed:
return _onChangedHandler;
}
Debug.Fail("Unknown FileSystemEvent change type! Value: " + changeType);
return null;
}
/// <summary>
/// Raises the event to each handler in the list.
/// </summary>
private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, ReadOnlySpan<char> name)
{
FileSystemEventHandler? handler = GetHandler(changeType);
if (handler != null && MatchPattern(name.IsEmpty ? _directory : name))
{
InvokeOn(new FileSystemEventArgs(changeType, _directory, name.IsEmpty ? null : name.ToString()), handler);
}
}
/// <summary>
/// Raises the event to each handler in the list.
/// </summary>
private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, string name)
{
FileSystemEventHandler? handler = GetHandler(changeType);
if (handler != null && MatchPattern(string.IsNullOrEmpty(name) ? _directory : name))
{
InvokeOn(new FileSystemEventArgs(changeType, _directory, name), handler);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Changed'/> event.
/// </devdoc>
protected void OnChanged(FileSystemEventArgs e)
{
InvokeOn(e, _onChangedHandler);
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Created'/> event.
/// </devdoc>
protected void OnCreated(FileSystemEventArgs e)
{
InvokeOn(e, _onCreatedHandler);
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Deleted'/> event.
/// </devdoc>
protected void OnDeleted(FileSystemEventArgs e)
{
InvokeOn(e, _onDeletedHandler);
}
private void InvokeOn(FileSystemEventArgs e, FileSystemEventHandler? handler)
{
if (handler != null)
{
ISynchronizeInvoke? syncObj = SynchronizingObject;
if (syncObj != null && syncObj.InvokeRequired)
syncObj.BeginInvoke(handler, new object[] { this, e });
else
handler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Error'/> event.
/// </devdoc>
protected void OnError(ErrorEventArgs e)
{
ErrorEventHandler? handler = _onErrorHandler;
if (handler != null)
{
ISynchronizeInvoke? syncObj = SynchronizingObject;
if (syncObj != null && syncObj.InvokeRequired)
syncObj.BeginInvoke(handler, new object[] { this, e });
else
handler(this, e);
}
}
/// <devdoc>
/// Raises the <see cref='System.IO.FileSystemWatcher.Renamed'/> event.
/// </devdoc>
protected void OnRenamed(RenamedEventArgs e)
{
RenamedEventHandler? handler = _onRenamedHandler;
if (handler != null)
{
ISynchronizeInvoke? syncObj = SynchronizingObject;
if (syncObj != null && syncObj.InvokeRequired)
syncObj.BeginInvoke(handler, new object[] { this, e });
else
handler(this, e);
}
}
public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) =>
WaitForChanged(changeType, Timeout.Infinite);
public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout)
{
// The full framework implementation doesn't do any argument validation, so
// none is done here, either.
var tcs = new TaskCompletionSource<WaitForChangedResult>();
FileSystemEventHandler? fseh = null;
RenamedEventHandler? reh = null;
// Register the event handlers based on what events are desired. The full framework
// doesn't register for the Error event, so this doesn't either.
if ((changeType & (WatcherChangeTypes.Created | WatcherChangeTypes.Deleted | WatcherChangeTypes.Changed)) != 0)
{
fseh = (s, e) =>
{
if ((e.ChangeType & changeType) != 0)
{
tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, oldName: null, timedOut: false));
}
};
if ((changeType & WatcherChangeTypes.Created) != 0)
Created += fseh;
if ((changeType & WatcherChangeTypes.Deleted) != 0)
Deleted += fseh;
if ((changeType & WatcherChangeTypes.Changed) != 0)
Changed += fseh;
}
if ((changeType & WatcherChangeTypes.Renamed) != 0)
{
reh = (s, e) =>
{
if ((e.ChangeType & changeType) != 0)
{
tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, e.OldName, timedOut: false));
}
};
Renamed += reh;
}
try
{
// Enable the FSW if it wasn't already.
bool wasEnabled = EnableRaisingEvents;
if (!wasEnabled)
{
EnableRaisingEvents = true;
}
// Block until an appropriate event arrives or until we timeout.
Debug.Assert(EnableRaisingEvents, "Expected EnableRaisingEvents to be true");
tcs.Task.Wait(timeout);
// Reset the enabled state to what it was.
EnableRaisingEvents = wasEnabled;
}
finally
{
// Unregister the event handlers.
if (reh != null)
{
Renamed -= reh;
}
if (fseh != null)
{
if ((changeType & WatcherChangeTypes.Changed) != 0)
Changed -= fseh;
if ((changeType & WatcherChangeTypes.Deleted) != 0)
Deleted -= fseh;
if ((changeType & WatcherChangeTypes.Created) != 0)
Created -= fseh;
}
}
// Return the results.
return tcs.Task.IsCompletedSuccessfully ?
tcs.Task.Result :
WaitForChangedResult.TimedOutResult;
}
public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, TimeSpan timeout) =>
WaitForChanged(changeType, ToTimeoutMilliseconds(timeout));
private static int ToTimeoutMilliseconds(TimeSpan timeout)
{
long totalMilliseconds = (long)timeout.TotalMilliseconds;
ArgumentOutOfRangeException.ThrowIfLessThan(totalMilliseconds, -1, nameof(timeout));
ArgumentOutOfRangeException.ThrowIfGreaterThan(totalMilliseconds, int.MaxValue, nameof(timeout));
return (int)totalMilliseconds;
}
/// <devdoc>
/// Stops and starts this object.
/// </devdoc>
/// <internalonly/>
private void Restart()
{
if ((!IsSuspended()) && _enabled)
{
StopRaisingEvents();
StartRaisingEventsIfNotDisposed();
}
}
private void StartRaisingEventsIfNotDisposed()
{
//Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed.
ObjectDisposedException.ThrowIf(_disposed, this);
StartRaisingEvents();
}
public override ISite? Site
{
get
{
return base.Site;
}
set
{
base.Site = value;
// set EnableRaisingEvents to true at design time so the user
// doesn't have to manually.
if (Site != null && Site.DesignMode)
EnableRaisingEvents = true;
}
}
public ISynchronizeInvoke? SynchronizingObject { get; set; }
public void BeginInit()
{
bool oldEnabled = _enabled;
StopRaisingEvents();
_enabled = oldEnabled;
_initializing = true;
}
public void EndInit()
{
_initializing = false;
// Start listening to events if _enabled was set to true at some point.
if (_directory.Length != 0 && _enabled)
StartRaisingEvents();
}
private bool IsSuspended()
{
return _initializing || DesignMode;
}
private sealed class NormalizedFilterCollection : Collection<string>
{
internal NormalizedFilterCollection() : base(new ImmutableStringList())
{
}
protected override void InsertItem(int index, string item)
{
base.InsertItem(index, string.IsNullOrEmpty(item) || item == "*.*" ? "*" : item);
}
protected override void SetItem(int index, string item)
{
base.SetItem(index, string.IsNullOrEmpty(item) || item == "*.*" ? "*" : item);
}
internal string[] GetFilters() => ((ImmutableStringList)Items).Items;
/// <summary>
/// List that maintains its underlying data in an immutable array, such that the list
/// will never modify an array returned from its Items property. This is to allow
/// the array to be enumerated safely while another thread might be concurrently mutating
/// the collection.
/// </summary>
private sealed class ImmutableStringList : IList<string>
{
public string[] Items = Array.Empty<string>();
public string this[int index]
{
get
{
string[] items = Items;
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual((uint)index, (uint)items.Length, nameof(index));
return items[index];
}
set
{
string[] clone = (string[])Items.Clone();
clone[index] = value;
Items = clone;
}
}
public int Count => Items.Length;
public bool IsReadOnly => false;
public void Add(string item)
{
// Collection<T> doesn't use this method.
throw new NotSupportedException();
}
public void Clear() => Items = Array.Empty<string>();
public bool Contains(string item) => Array.IndexOf(Items, item) != -1;
public void CopyTo(string[] array, int arrayIndex) => Items.CopyTo(array, arrayIndex);
public IEnumerator<string> GetEnumerator() => ((IEnumerable<string>)Items).GetEnumerator();
public int IndexOf(string item) => Array.IndexOf(Items, item);
public void Insert(int index, string item)
{
string[] items = Items;
string[] newItems = new string[items.Length + 1];
items.AsSpan(0, index).CopyTo(newItems);
items.AsSpan(index).CopyTo(newItems.AsSpan(index + 1));
newItems[index] = item;
Items = newItems;
}
public bool Remove(string item)
{
// Collection<T> doesn't use this method.
throw new NotSupportedException();
}
public void RemoveAt(int index)
{
string[] items = Items;
string[] newItems = new string[items.Length - 1];
items.AsSpan(0, index).CopyTo(newItems);
items.AsSpan(index + 1).CopyTo(newItems.AsSpan(index));
Items = newItems;
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
}
}