├── .gitignore ├── .vscode └── settings.json ├── FileSystemSafeWatcher.cs ├── LICENSE ├── README.md └── dev ├── DevelopingConsoleApp.sln └── DevelopingConsoleApp ├── DevelopingConsoleApp.csproj ├── FileSystemSafeWatcher.cs └── Program.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | 11 | [Dd]ebug/ 12 | [Rr]elease/ 13 | x64/ 14 | [Bb]in/ 15 | [Oo]bj/ 16 | 17 | # MSTest test Results 18 | [Tt]est[Rr]esult*/ 19 | [Bb]uild[Ll]og.* 20 | 21 | *_i.c 22 | *_p.c 23 | *_i.h 24 | *.ilk 25 | *.meta 26 | *.obj 27 | *.pch 28 | *.pdb 29 | *.pgc 30 | *.pgd 31 | *.rsp 32 | *.sbr 33 | *.tlb 34 | *.tli 35 | *.tlh 36 | *.tmp 37 | *.tmp_proj 38 | *.log 39 | *.vspscc 40 | *.vssscc 41 | .builds 42 | *.pidb 43 | *.log 44 | *.svclog 45 | *.scc 46 | 47 | # Visual C++ cache files 48 | ipch/ 49 | *.aps 50 | *.ncb 51 | *.opensdf 52 | *.sdf 53 | *.cachefile 54 | 55 | # Visual Studio profiler 56 | *.psess 57 | *.vsp 58 | *.vspx 59 | 60 | # Guidance Automation Toolkit 61 | *.gpState 62 | 63 | # ReSharper is a .NET coding add-in 64 | _ReSharper*/ 65 | *.[Rr]e[Ss]harper 66 | *.DotSettings.user 67 | 68 | # Click-Once directory 69 | publish/ 70 | 71 | # Publish Web Output 72 | *.Publish.xml 73 | *.pubxml 74 | *.azurePubxml 75 | 76 | # NuGet Packages Directory 77 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 78 | packages/ 79 | ## TODO: If the tool you use requires repositories.config, also uncomment the next line 80 | !packages/repositories.config 81 | 82 | # Windows Azure Build Output 83 | csx/ 84 | *.build.csdef 85 | 86 | # Windows Store app package directory 87 | AppPackages/ 88 | 89 | # Others 90 | sql/ 91 | *.Cache 92 | ClientBin/ 93 | [Ss]tyle[Cc]op.* 94 | ![Ss]tyle[Cc]op.targets 95 | ~$* 96 | *~ 97 | *.dbmdl 98 | *.[Pp]ublish.xml 99 | 100 | *.publishsettings 101 | 102 | # RIA/Silverlight projects 103 | Generated_Code/ 104 | 105 | # Backup & report files from converting an old project file to a newer 106 | # Visual Studio version. Backup files are not needed, because we have git ;-) 107 | _UpgradeReport_Files/ 108 | Backup*/ 109 | UpgradeLog*.XML 110 | UpgradeLog*.htm 111 | 112 | # SQL Server files 113 | App_Data/*.mdf 114 | App_Data/*.ldf 115 | 116 | # ========================= 117 | # Windows detritus 118 | # ========================= 119 | 120 | # Windows image file caches 121 | Thumbs.db 122 | ehthumbs.db 123 | 124 | # Folder config file 125 | Desktop.ini 126 | 127 | # Recycle Bin used on file shares 128 | $RECYCLE.BIN/ 129 | 130 | # Mac desktop service store files 131 | .DS_Store 132 | 133 | _NCrunch* 134 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "dotnet.defaultSolution": "dev/DevelopingConsoleApp.sln" 3 | } -------------------------------------------------------------------------------- /FileSystemSafeWatcher.cs: -------------------------------------------------------------------------------- 1 | // DISCLAIMER: Use this code at your own risk. 2 | // No support is provided and this code has NOT been tested. 3 | 4 | using System.Timers; 5 | using System.Collections; 6 | using System.ComponentModel; 7 | using System.Collections.ObjectModel; 8 | 9 | namespace Menelabs 10 | { 11 | 12 | /// 13 | /// This class wraps a FileSystemWatcher object. The class is not derived 14 | /// from FileSystemWatcher because most of the FileSystemWatcher methods 15 | /// are not virtual. The class was designed to resemble FileSystemWatcher class 16 | /// as much as possible so that you can use FileSystemSafeWatcher instead 17 | /// of FileSystemWatcher objects. 18 | /// FileSystemSafeWatcher will capture all events from the FileSystemWatcher object. 19 | /// The captured events will be delayed by at least ConsolidationInterval milliseconds in order 20 | /// to be able to eliminate duplicate events. When duplicate events are found, the last event 21 | /// is droped and the first event is fired (the reverse is not recomended because it could 22 | /// cause some events not be fired at all since the last event will become the first event and 23 | /// it won't fire a if a new similar event arrives imediately afterwards). 24 | /// 25 | public class FileSystemSafeWatcher : IDisposable 26 | { 27 | private readonly FileSystemWatcher _fileSystemWatcher; 28 | 29 | /// 30 | /// Lock order is _enterThread, _events.SyncRoot 31 | /// 32 | private readonly object _enterThread = new object(); // Only one timer event is processed at any given moment 33 | private ArrayList _events; 34 | 35 | private System.Timers.Timer _serverTimer; 36 | private int _consolidationInterval = 1000; // milliseconds 37 | 38 | #region Delegate to FileSystemWatcher 39 | 40 | public FileSystemSafeWatcher() 41 | { 42 | _fileSystemWatcher = new FileSystemWatcher(); 43 | Initialize(); 44 | } 45 | 46 | public FileSystemSafeWatcher(string path) 47 | { 48 | _fileSystemWatcher = new FileSystemWatcher(path); 49 | Initialize(); 50 | } 51 | 52 | public FileSystemSafeWatcher(string path, string filter) 53 | { 54 | _fileSystemWatcher = new FileSystemWatcher(path, filter); 55 | Initialize(); 56 | } 57 | 58 | /// 59 | /// Gets or sets a value indicating whether the component is enabled. 60 | /// 61 | /// true if the component is enabled; otherwise, false. The default is false. If you are using the component on a designer in Visual Studio 2005, the default is true. 62 | public bool EnableRaisingEvents 63 | { 64 | get 65 | { 66 | return _fileSystemWatcher.EnableRaisingEvents; 67 | } 68 | set 69 | { 70 | _fileSystemWatcher.EnableRaisingEvents = value; 71 | if (value) 72 | { 73 | _serverTimer.Start(); 74 | } 75 | else 76 | { 77 | _serverTimer.Stop(); 78 | _events.Clear(); 79 | } 80 | } 81 | } 82 | 83 | /// 84 | /// Gets or sets the filter string, used to determine what files are monitored in a directory. 85 | /// 86 | /// The filter string. The default is "*.*" (Watches all files.) 87 | public string Filter 88 | { 89 | get 90 | { 91 | return _fileSystemWatcher.Filter; 92 | } 93 | set 94 | { 95 | _fileSystemWatcher.Filter = value; 96 | } 97 | } 98 | 99 | public Collection Filters 100 | { 101 | get 102 | { 103 | return _fileSystemWatcher.Filters; 104 | } 105 | } 106 | 107 | /// 108 | /// Gets or sets a value indicating whether subdirectories within the specified path should be monitored. 109 | /// 110 | /// true if you want to monitor subdirectories; otherwise, false. The default is false. 111 | public bool IncludeSubdirectories 112 | { 113 | get 114 | { 115 | return _fileSystemWatcher.IncludeSubdirectories; 116 | } 117 | set 118 | { 119 | _fileSystemWatcher.IncludeSubdirectories = value; 120 | } 121 | } 122 | 123 | /// 124 | /// Gets or sets the size of the internal buffer. 125 | /// 126 | /// The internal buffer size. The default is 8192 (8K). 127 | public int InternalBufferSize 128 | { 129 | get 130 | { 131 | return _fileSystemWatcher.InternalBufferSize; 132 | } 133 | set 134 | { 135 | _fileSystemWatcher.InternalBufferSize = value; 136 | } 137 | } 138 | 139 | /// 140 | /// Gets or sets the type of changes to watch for. 141 | /// 142 | /// One of the System.IO.NotifyFilters values. The default is the bitwise OR combination of LastWrite, FileName, and DirectoryName. 143 | /// The value is not a valid bitwise OR combination of the System.IO.NotifyFilters values. 144 | public NotifyFilters NotifyFilter 145 | { 146 | get 147 | { 148 | return _fileSystemWatcher.NotifyFilter; 149 | } 150 | set 151 | { 152 | _fileSystemWatcher.NotifyFilter = value; 153 | } 154 | } 155 | 156 | /// 157 | /// Gets or sets the path of the directory to watch. 158 | /// 159 | /// The path to monitor. The default is an empty string (""). 160 | /// The specified path contains wildcard characters.-or- The specified path contains invalid path characters. 161 | public string Path 162 | { 163 | get 164 | { 165 | return _fileSystemWatcher.Path; 166 | } 167 | set 168 | { 169 | _fileSystemWatcher.Path = value; 170 | } 171 | } 172 | 173 | /// 174 | /// Gets or sets the object used to marshal the event handler calls issued as a result of a directory change. 175 | /// 176 | /// The System.ComponentModel.ISynchronizeInvoke that represents the object used to marshal the event handler calls issued as a result of a directory change. The default is null. 177 | public ISynchronizeInvoke SynchronizingObject 178 | { 179 | get 180 | { 181 | return _fileSystemWatcher.SynchronizingObject; 182 | } 183 | set 184 | { 185 | _fileSystemWatcher.SynchronizingObject = value; 186 | } 187 | } 188 | 189 | /// 190 | /// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is changed. 191 | /// 192 | public event FileSystemEventHandler Changed; 193 | 194 | /// 195 | /// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is created. 196 | /// 197 | public event FileSystemEventHandler Created; 198 | 199 | /// 200 | /// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is deleted. 201 | /// 202 | public event FileSystemEventHandler Deleted; 203 | 204 | /// 205 | /// Occurs when the internal buffer overflows. 206 | /// 207 | public event ErrorEventHandler Error; 208 | 209 | /// 210 | /// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is renamed. 211 | /// 212 | public event RenamedEventHandler Renamed; 213 | 214 | /// 215 | /// Begins the initialization of a System.IO.FileSystemWatcher used on a form or used by another component. The initialization occurs at run time. 216 | /// 217 | public void BeginInit() 218 | { 219 | _fileSystemWatcher.BeginInit(); 220 | } 221 | 222 | /// 223 | /// Releases the unmanaged resources used by the System.IO.FileSystemWatcher and optionally releases the managed resources. 224 | /// 225 | public void Dispose() 226 | { 227 | Uninitialize(); 228 | } 229 | 230 | /// 231 | /// Ends the initialization of a System.IO.FileSystemWatcher used on a form or used by another component. The initialization occurs at run time. 232 | /// 233 | public void EndInit() 234 | { 235 | _fileSystemWatcher.EndInit(); 236 | } 237 | 238 | /// 239 | /// Raises the System.IO.FileSystemWatcher.Changed event. 240 | /// 241 | /// A System.IO.FileSystemEventArgs that contains the event data. 242 | protected void OnChanged(FileSystemEventArgs e) 243 | { 244 | if (Changed != null) 245 | Changed(this, e); 246 | } 247 | 248 | /// 249 | /// Raises the System.IO.FileSystemWatcher.Created event. 250 | /// 251 | /// A System.IO.FileSystemEventArgs that contains the event data. 252 | protected void OnCreated(FileSystemEventArgs e) 253 | { 254 | if (Created != null) 255 | Created(this, e); 256 | } 257 | 258 | /// 259 | /// Raises the System.IO.FileSystemWatcher.Deleted event. 260 | /// 261 | /// A System.IO.FileSystemEventArgs that contains the event data. 262 | protected void OnDeleted(FileSystemEventArgs e) 263 | { 264 | if (Deleted != null) 265 | Deleted(this, e); 266 | } 267 | 268 | /// 269 | /// Raises the System.IO.FileSystemWatcher.Error event. 270 | /// 271 | /// An System.IO.ErrorEventArgs that contains the event data. 272 | protected void OnError(ErrorEventArgs e) 273 | { 274 | if (Error != null) 275 | Error(this, e); 276 | } 277 | 278 | /// 279 | /// Raises the System.IO.FileSystemWatcher.Renamed event. 280 | /// 281 | /// A System.IO.RenamedEventArgs that contains the event data. 282 | protected void OnRenamed(RenamedEventArgs e) 283 | { 284 | if (Renamed != null) 285 | Renamed(this, e); 286 | } 287 | 288 | /// 289 | /// A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor. 290 | /// 291 | /// The System.IO.WatcherChangeTypes to watch for. 292 | /// A System.IO.WaitForChangedResult that contains specific information on the change that occurred. 293 | public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) 294 | { 295 | //TODO 296 | throw new NotImplementedException(); 297 | } 298 | 299 | /// 300 | /// A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor 301 | /// and the time (in milliseconds) to wait before timing out. 302 | /// 303 | /// The System.IO.WatcherChangeTypes to watch for. 304 | /// The time (in milliseconds) to wait before timing out. 305 | /// A System.IO.WaitForChangedResult that contains specific information on the change that occurred. 306 | public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) 307 | { 308 | //TODO 309 | throw new NotImplementedException(); 310 | } 311 | 312 | #endregion 313 | 314 | #region Implementation 315 | 316 | private void Initialize() 317 | { 318 | _events = ArrayList.Synchronized(new ArrayList(32)); 319 | _fileSystemWatcher.Changed += new FileSystemEventHandler(this.FileSystemEventHandler); 320 | _fileSystemWatcher.Created += new FileSystemEventHandler(this.FileSystemEventHandler); 321 | _fileSystemWatcher.Deleted += new FileSystemEventHandler(this.FileSystemEventHandler); 322 | _fileSystemWatcher.Error += new ErrorEventHandler(this.ErrorEventHandler); 323 | _fileSystemWatcher.Renamed += new RenamedEventHandler(this.RenamedEventHandler); 324 | _serverTimer = new System.Timers.Timer(_consolidationInterval); 325 | _serverTimer.Elapsed += new ElapsedEventHandler(this.ElapsedEventHandler); 326 | _serverTimer.AutoReset = true; 327 | _serverTimer.Enabled = _fileSystemWatcher.EnableRaisingEvents; 328 | } 329 | 330 | private void Uninitialize() 331 | { 332 | if (_fileSystemWatcher != null) 333 | _fileSystemWatcher.Dispose(); 334 | if (_serverTimer != null) 335 | _serverTimer.Dispose(); 336 | } 337 | 338 | private void FileSystemEventHandler(object sender, FileSystemEventArgs e) 339 | { 340 | _events.Add(new DelayedEvent(e)); 341 | } 342 | 343 | private void ErrorEventHandler(object sender, ErrorEventArgs e) 344 | { 345 | OnError(e); 346 | } 347 | 348 | private void RenamedEventHandler(object sender, RenamedEventArgs e) 349 | { 350 | _events.Add(new DelayedEvent(e)); 351 | } 352 | 353 | private void ElapsedEventHandler(Object sender, ElapsedEventArgs e) 354 | { 355 | // We don't fire the events inside the lock. We will queue them here until 356 | // the code exits the locks. 357 | Queue eventsToBeFired = null; 358 | if (System.Threading.Monitor.TryEnter(_enterThread)) 359 | { 360 | // Only one thread at a time is processing the events 361 | try 362 | { 363 | eventsToBeFired = new Queue(32); 364 | // Lock the collection while processing the events 365 | lock (_events.SyncRoot) 366 | { 367 | DelayedEvent current; 368 | for (int i = 0; i < _events.Count; i++) 369 | { 370 | current = _events[i] as DelayedEvent; 371 | if (current.Delayed) 372 | { 373 | // This event has been delayed already so we can fire it 374 | // We just need to remove any duplicates 375 | for (int j = i + 1; j < _events.Count; j++) 376 | { 377 | if (current.IsDuplicate(_events[j])) 378 | { 379 | // Removing later duplicates 380 | _events.RemoveAt(j); 381 | j--; // Don't skip next event 382 | } 383 | } 384 | 385 | bool raiseEvent = true; 386 | if ((current.Args.ChangeType == WatcherChangeTypes.Created || current.Args.ChangeType == WatcherChangeTypes.Changed) 387 | && File.Exists(current.Args.FullPath)) 388 | { 389 | //check if the file has been completely copied (can be opened for read) 390 | FileStream stream = null; 391 | try 392 | { 393 | stream = File.Open(current.Args.FullPath, FileMode.Open, FileAccess.Read, FileShare.None); 394 | // If this succeeds, the file is finished 395 | } 396 | catch (IOException) 397 | { 398 | raiseEvent = false; 399 | } 400 | finally 401 | { 402 | if (stream != null) stream.Close(); 403 | } 404 | } 405 | 406 | if (raiseEvent) 407 | { 408 | // Add the event to the list of events to be fired 409 | eventsToBeFired.Enqueue(current); 410 | // Remove it from the current list 411 | _events.RemoveAt(i); 412 | i--; // Don't skip next event 413 | } 414 | } 415 | else 416 | { 417 | // This event was not delayed yet, so we will delay processing 418 | // this event for at least one timer interval 419 | current.Delayed = true; 420 | } 421 | } 422 | } 423 | } 424 | finally 425 | { 426 | System.Threading.Monitor.Exit(_enterThread); 427 | } 428 | } 429 | // else - this timer event was skipped, processing will happen during the next timer event 430 | 431 | // Now fire all the events if any events are in eventsToBeFired 432 | RaiseEvents(eventsToBeFired); 433 | } 434 | 435 | public int ConsolidationInterval 436 | { 437 | get 438 | { 439 | return _consolidationInterval; 440 | } 441 | set 442 | { 443 | _consolidationInterval = value; 444 | _serverTimer.Interval = value; 445 | } 446 | } 447 | 448 | protected void RaiseEvents(Queue deQueue) 449 | { 450 | if ((deQueue != null) && (deQueue.Count > 0)) 451 | { 452 | DelayedEvent de; 453 | while (deQueue.Count > 0) 454 | { 455 | de = deQueue.Dequeue() as DelayedEvent; 456 | switch (de.Args.ChangeType) 457 | { 458 | case WatcherChangeTypes.Changed: 459 | OnChanged(de.Args); 460 | break; 461 | case WatcherChangeTypes.Created: 462 | OnCreated(de.Args); 463 | break; 464 | case WatcherChangeTypes.Deleted: 465 | OnDeleted(de.Args); 466 | break; 467 | case WatcherChangeTypes.Renamed: 468 | OnRenamed(de.Args as RenamedEventArgs); 469 | break; 470 | } 471 | } 472 | } 473 | } 474 | #endregion 475 | } 476 | 477 | /// 478 | /// This class wraps FileSystemEventArgs and RenamedEventArgs objects and detection of duplicate events. 479 | /// 480 | public class DelayedEvent 481 | { 482 | private readonly FileSystemEventArgs _args; 483 | 484 | /// 485 | /// Only delayed events that are unique will be fired. 486 | /// 487 | private bool _delayed; 488 | 489 | 490 | public DelayedEvent(FileSystemEventArgs args) 491 | { 492 | _delayed = false; 493 | _args = args; 494 | } 495 | 496 | public FileSystemEventArgs Args 497 | { 498 | get 499 | { 500 | return _args; 501 | } 502 | } 503 | 504 | public bool Delayed 505 | { 506 | get 507 | { 508 | return _delayed; 509 | } 510 | set 511 | { 512 | _delayed = value; 513 | } 514 | } 515 | 516 | public virtual bool IsDuplicate(object obj) 517 | { 518 | DelayedEvent delayedEvent = obj as DelayedEvent; 519 | if (delayedEvent == null) 520 | return false; // this is not null so they are different 521 | FileSystemEventArgs eO1 = _args; 522 | RenamedEventArgs reO1 = _args as RenamedEventArgs; 523 | FileSystemEventArgs eO2 = delayedEvent._args; 524 | RenamedEventArgs reO2 = delayedEvent._args as RenamedEventArgs; 525 | // The events are equal only if they are of the same type (reO1 and reO2 526 | // are both null or NOT NULL) and have all properties equal. 527 | // We also eliminate Changed events that follow recent Created events 528 | // because many apps create new files by creating an empty file and then 529 | // they update the file with the file content. 530 | return ((eO1 != null && eO2 != null && eO1.ChangeType == eO2.ChangeType 531 | && eO1.FullPath == eO2.FullPath && eO1.Name == eO2.Name) && 532 | ((reO1 == null && reO2 == null) || (reO1 != null && reO2 != null && 533 | reO1.OldFullPath == reO2.OldFullPath && reO1.OldName == reO2.OldName))) || 534 | (eO1 != null && eO2 != null && eO1.ChangeType == WatcherChangeTypes.Created 535 | && eO2.ChangeType == WatcherChangeTypes.Changed 536 | && eO1.FullPath == eO2.FullPath && eO1.Name == eO2.Name); 537 | } 538 | } 539 | 540 | } 541 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | FileSystemSafeWatcher 2 | ===================== 3 | 4 | Extends the FileSystemWatcher to trigger the events only when the file is ready for read 5 | 6 | ## Usage 7 | It has the same interface as the FileSystemWatcher. 8 | 9 | You may find an example here https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?view=netcore-3.1 10 | -------------------------------------------------------------------------------- /dev/DevelopingConsoleApp.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DevelopingConsoleApp", "DevelopingConsoleApp\DevelopingConsoleApp.csproj", "{33715FDB-E0E5-485E-A50D-FAAA61F7F1AF}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(SolutionProperties) = preSolution 14 | HideSolutionNode = FALSE 15 | EndGlobalSection 16 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 17 | {33715FDB-E0E5-485E-A50D-FAAA61F7F1AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 18 | {33715FDB-E0E5-485E-A50D-FAAA61F7F1AF}.Debug|Any CPU.Build.0 = Debug|Any CPU 19 | {33715FDB-E0E5-485E-A50D-FAAA61F7F1AF}.Release|Any CPU.ActiveCfg = Release|Any CPU 20 | {33715FDB-E0E5-485E-A50D-FAAA61F7F1AF}.Release|Any CPU.Build.0 = Release|Any CPU 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /dev/DevelopingConsoleApp/DevelopingConsoleApp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /dev/DevelopingConsoleApp/FileSystemSafeWatcher.cs: -------------------------------------------------------------------------------- 1 | // DISCLAIMER: Use this code at your own risk. 2 | // No support is provided and this code has NOT been tested. 3 | 4 | using System.Timers; 5 | using System.Collections; 6 | using System.ComponentModel; 7 | using System.Collections.ObjectModel; 8 | 9 | namespace Menelabs 10 | { 11 | 12 | /// 13 | /// This class wraps a FileSystemWatcher object. The class is not derived 14 | /// from FileSystemWatcher because most of the FileSystemWatcher methods 15 | /// are not virtual. The class was designed to resemble FileSystemWatcher class 16 | /// as much as possible so that you can use FileSystemSafeWatcher instead 17 | /// of FileSystemWatcher objects. 18 | /// FileSystemSafeWatcher will capture all events from the FileSystemWatcher object. 19 | /// The captured events will be delayed by at least ConsolidationInterval milliseconds in order 20 | /// to be able to eliminate duplicate events. When duplicate events are found, the last event 21 | /// is droped and the first event is fired (the reverse is not recomended because it could 22 | /// cause some events not be fired at all since the last event will become the first event and 23 | /// it won't fire a if a new similar event arrives imediately afterwards). 24 | /// 25 | public class FileSystemSafeWatcher : IDisposable 26 | { 27 | private readonly FileSystemWatcher _fileSystemWatcher; 28 | 29 | /// 30 | /// Lock order is _enterThread, _events.SyncRoot 31 | /// 32 | private readonly object _enterThread = new object(); // Only one timer event is processed at any given moment 33 | private ArrayList _events; 34 | 35 | private System.Timers.Timer _serverTimer; 36 | private int _consolidationInterval = 1000; // milliseconds 37 | 38 | #region Delegate to FileSystemWatcher 39 | 40 | public FileSystemSafeWatcher() 41 | { 42 | _fileSystemWatcher = new FileSystemWatcher(); 43 | Initialize(); 44 | } 45 | 46 | public FileSystemSafeWatcher(string path) 47 | { 48 | _fileSystemWatcher = new FileSystemWatcher(path); 49 | Initialize(); 50 | } 51 | 52 | public FileSystemSafeWatcher(string path, string filter) 53 | { 54 | _fileSystemWatcher = new FileSystemWatcher(path, filter); 55 | Initialize(); 56 | } 57 | 58 | /// 59 | /// Gets or sets a value indicating whether the component is enabled. 60 | /// 61 | /// true if the component is enabled; otherwise, false. The default is false. If you are using the component on a designer in Visual Studio 2005, the default is true. 62 | public bool EnableRaisingEvents 63 | { 64 | get 65 | { 66 | return _fileSystemWatcher.EnableRaisingEvents; 67 | } 68 | set 69 | { 70 | _fileSystemWatcher.EnableRaisingEvents = value; 71 | if (value) 72 | { 73 | _serverTimer.Start(); 74 | } 75 | else 76 | { 77 | _serverTimer.Stop(); 78 | _events.Clear(); 79 | } 80 | } 81 | } 82 | 83 | /// 84 | /// Gets or sets the filter string, used to determine what files are monitored in a directory. 85 | /// 86 | /// The filter string. The default is "*.*" (Watches all files.) 87 | public string Filter 88 | { 89 | get 90 | { 91 | return _fileSystemWatcher.Filter; 92 | } 93 | set 94 | { 95 | _fileSystemWatcher.Filter = value; 96 | } 97 | } 98 | 99 | public Collection Filters 100 | { 101 | get 102 | { 103 | return _fileSystemWatcher.Filters; 104 | } 105 | } 106 | 107 | /// 108 | /// Gets or sets a value indicating whether subdirectories within the specified path should be monitored. 109 | /// 110 | /// true if you want to monitor subdirectories; otherwise, false. The default is false. 111 | public bool IncludeSubdirectories 112 | { 113 | get 114 | { 115 | return _fileSystemWatcher.IncludeSubdirectories; 116 | } 117 | set 118 | { 119 | _fileSystemWatcher.IncludeSubdirectories = value; 120 | } 121 | } 122 | 123 | /// 124 | /// Gets or sets the size of the internal buffer. 125 | /// 126 | /// The internal buffer size. The default is 8192 (8K). 127 | public int InternalBufferSize 128 | { 129 | get 130 | { 131 | return _fileSystemWatcher.InternalBufferSize; 132 | } 133 | set 134 | { 135 | _fileSystemWatcher.InternalBufferSize = value; 136 | } 137 | } 138 | 139 | /// 140 | /// Gets or sets the type of changes to watch for. 141 | /// 142 | /// One of the System.IO.NotifyFilters values. The default is the bitwise OR combination of LastWrite, FileName, and DirectoryName. 143 | /// The value is not a valid bitwise OR combination of the System.IO.NotifyFilters values. 144 | public NotifyFilters NotifyFilter 145 | { 146 | get 147 | { 148 | return _fileSystemWatcher.NotifyFilter; 149 | } 150 | set 151 | { 152 | _fileSystemWatcher.NotifyFilter = value; 153 | } 154 | } 155 | 156 | /// 157 | /// Gets or sets the path of the directory to watch. 158 | /// 159 | /// The path to monitor. The default is an empty string (""). 160 | /// The specified path contains wildcard characters.-or- The specified path contains invalid path characters. 161 | public string Path 162 | { 163 | get 164 | { 165 | return _fileSystemWatcher.Path; 166 | } 167 | set 168 | { 169 | _fileSystemWatcher.Path = value; 170 | } 171 | } 172 | 173 | /// 174 | /// Gets or sets the object used to marshal the event handler calls issued as a result of a directory change. 175 | /// 176 | /// The System.ComponentModel.ISynchronizeInvoke that represents the object used to marshal the event handler calls issued as a result of a directory change. The default is null. 177 | public ISynchronizeInvoke SynchronizingObject 178 | { 179 | get 180 | { 181 | return _fileSystemWatcher.SynchronizingObject; 182 | } 183 | set 184 | { 185 | _fileSystemWatcher.SynchronizingObject = value; 186 | } 187 | } 188 | 189 | /// 190 | /// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is changed. 191 | /// 192 | public event FileSystemEventHandler Changed; 193 | 194 | /// 195 | /// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is created. 196 | /// 197 | public event FileSystemEventHandler Created; 198 | 199 | /// 200 | /// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is deleted. 201 | /// 202 | public event FileSystemEventHandler Deleted; 203 | 204 | /// 205 | /// Occurs when the internal buffer overflows. 206 | /// 207 | public event ErrorEventHandler Error; 208 | 209 | /// 210 | /// Occurs when a file or directory in the specified System.IO.FileSystemWatcher.Path is renamed. 211 | /// 212 | public event RenamedEventHandler Renamed; 213 | 214 | /// 215 | /// Begins the initialization of a System.IO.FileSystemWatcher used on a form or used by another component. The initialization occurs at run time. 216 | /// 217 | public void BeginInit() 218 | { 219 | _fileSystemWatcher.BeginInit(); 220 | } 221 | 222 | /// 223 | /// Releases the unmanaged resources used by the System.IO.FileSystemWatcher and optionally releases the managed resources. 224 | /// 225 | public void Dispose() 226 | { 227 | Uninitialize(); 228 | } 229 | 230 | /// 231 | /// Ends the initialization of a System.IO.FileSystemWatcher used on a form or used by another component. The initialization occurs at run time. 232 | /// 233 | public void EndInit() 234 | { 235 | _fileSystemWatcher.EndInit(); 236 | } 237 | 238 | /// 239 | /// Raises the System.IO.FileSystemWatcher.Changed event. 240 | /// 241 | /// A System.IO.FileSystemEventArgs that contains the event data. 242 | protected void OnChanged(FileSystemEventArgs e) 243 | { 244 | if (Changed != null) 245 | Changed(this, e); 246 | } 247 | 248 | /// 249 | /// Raises the System.IO.FileSystemWatcher.Created event. 250 | /// 251 | /// A System.IO.FileSystemEventArgs that contains the event data. 252 | protected void OnCreated(FileSystemEventArgs e) 253 | { 254 | if (Created != null) 255 | Created(this, e); 256 | } 257 | 258 | /// 259 | /// Raises the System.IO.FileSystemWatcher.Deleted event. 260 | /// 261 | /// A System.IO.FileSystemEventArgs that contains the event data. 262 | protected void OnDeleted(FileSystemEventArgs e) 263 | { 264 | if (Deleted != null) 265 | Deleted(this, e); 266 | } 267 | 268 | /// 269 | /// Raises the System.IO.FileSystemWatcher.Error event. 270 | /// 271 | /// An System.IO.ErrorEventArgs that contains the event data. 272 | protected void OnError(ErrorEventArgs e) 273 | { 274 | if (Error != null) 275 | Error(this, e); 276 | } 277 | 278 | /// 279 | /// Raises the System.IO.FileSystemWatcher.Renamed event. 280 | /// 281 | /// A System.IO.RenamedEventArgs that contains the event data. 282 | protected void OnRenamed(RenamedEventArgs e) 283 | { 284 | if (Renamed != null) 285 | Renamed(this, e); 286 | } 287 | 288 | /// 289 | /// A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor. 290 | /// 291 | /// The System.IO.WatcherChangeTypes to watch for. 292 | /// A System.IO.WaitForChangedResult that contains specific information on the change that occurred. 293 | public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) 294 | { 295 | //TODO 296 | throw new NotImplementedException(); 297 | } 298 | 299 | /// 300 | /// A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor 301 | /// and the time (in milliseconds) to wait before timing out. 302 | /// 303 | /// The System.IO.WatcherChangeTypes to watch for. 304 | /// The time (in milliseconds) to wait before timing out. 305 | /// A System.IO.WaitForChangedResult that contains specific information on the change that occurred. 306 | public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) 307 | { 308 | //TODO 309 | throw new NotImplementedException(); 310 | } 311 | 312 | #endregion 313 | 314 | #region Implementation 315 | 316 | private void Initialize() 317 | { 318 | _events = ArrayList.Synchronized(new ArrayList(32)); 319 | _fileSystemWatcher.Changed += new FileSystemEventHandler(this.FileSystemEventHandler); 320 | _fileSystemWatcher.Created += new FileSystemEventHandler(this.FileSystemEventHandler); 321 | _fileSystemWatcher.Deleted += new FileSystemEventHandler(this.FileSystemEventHandler); 322 | _fileSystemWatcher.Error += new ErrorEventHandler(this.ErrorEventHandler); 323 | _fileSystemWatcher.Renamed += new RenamedEventHandler(this.RenamedEventHandler); 324 | _serverTimer = new System.Timers.Timer(_consolidationInterval); 325 | _serverTimer.Elapsed += new ElapsedEventHandler(this.ElapsedEventHandler); 326 | _serverTimer.AutoReset = true; 327 | _serverTimer.Enabled = _fileSystemWatcher.EnableRaisingEvents; 328 | } 329 | 330 | private void Uninitialize() 331 | { 332 | if (_fileSystemWatcher != null) 333 | _fileSystemWatcher.Dispose(); 334 | if (_serverTimer != null) 335 | _serverTimer.Dispose(); 336 | } 337 | 338 | private void FileSystemEventHandler(object sender, FileSystemEventArgs e) 339 | { 340 | _events.Add(new DelayedEvent(e)); 341 | } 342 | 343 | private void ErrorEventHandler(object sender, ErrorEventArgs e) 344 | { 345 | OnError(e); 346 | } 347 | 348 | private void RenamedEventHandler(object sender, RenamedEventArgs e) 349 | { 350 | _events.Add(new DelayedEvent(e)); 351 | } 352 | 353 | private void ElapsedEventHandler(Object sender, ElapsedEventArgs e) 354 | { 355 | // We don't fire the events inside the lock. We will queue them here until 356 | // the code exits the locks. 357 | Queue eventsToBeFired = null; 358 | if (System.Threading.Monitor.TryEnter(_enterThread)) 359 | { 360 | // Only one thread at a time is processing the events 361 | try 362 | { 363 | eventsToBeFired = new Queue(32); 364 | // Lock the collection while processing the events 365 | lock (_events.SyncRoot) 366 | { 367 | DelayedEvent current; 368 | for (int i = 0; i < _events.Count; i++) 369 | { 370 | current = _events[i] as DelayedEvent; 371 | if (current.Delayed) 372 | { 373 | // This event has been delayed already so we can fire it 374 | // We just need to remove any duplicates 375 | for (int j = i + 1; j < _events.Count; j++) 376 | { 377 | if (current.IsDuplicate(_events[j])) 378 | { 379 | // Removing later duplicates 380 | _events.RemoveAt(j); 381 | j--; // Don't skip next event 382 | } 383 | } 384 | 385 | bool raiseEvent = true; 386 | if (current.Args.ChangeType == WatcherChangeTypes.Created || current.Args.ChangeType == WatcherChangeTypes.Changed) 387 | { 388 | //check if the file has been completely copied (can be opened for read) 389 | FileStream stream = null; 390 | try 391 | { 392 | stream = File.Open(current.Args.FullPath, FileMode.Open, FileAccess.Read, FileShare.None); 393 | // If this succeeds, the file is finished 394 | } 395 | catch (IOException) 396 | { 397 | raiseEvent = false; 398 | } 399 | finally 400 | { 401 | if (stream != null) stream.Close(); 402 | } 403 | } 404 | 405 | if (raiseEvent) 406 | { 407 | // Add the event to the list of events to be fired 408 | eventsToBeFired.Enqueue(current); 409 | // Remove it from the current list 410 | _events.RemoveAt(i); 411 | i--; // Don't skip next event 412 | } 413 | } 414 | else 415 | { 416 | // This event was not delayed yet, so we will delay processing 417 | // this event for at least one timer interval 418 | current.Delayed = true; 419 | } 420 | } 421 | } 422 | } 423 | finally 424 | { 425 | System.Threading.Monitor.Exit(_enterThread); 426 | } 427 | } 428 | // else - this timer event was skipped, processing will happen during the next timer event 429 | 430 | // Now fire all the events if any events are in eventsToBeFired 431 | RaiseEvents(eventsToBeFired); 432 | } 433 | 434 | public int ConsolidationInterval 435 | { 436 | get 437 | { 438 | return _consolidationInterval; 439 | } 440 | set 441 | { 442 | _consolidationInterval = value; 443 | _serverTimer.Interval = value; 444 | } 445 | } 446 | 447 | protected void RaiseEvents(Queue deQueue) 448 | { 449 | if ((deQueue != null) && (deQueue.Count > 0)) 450 | { 451 | DelayedEvent de; 452 | while (deQueue.Count > 0) 453 | { 454 | de = deQueue.Dequeue() as DelayedEvent; 455 | switch (de.Args.ChangeType) 456 | { 457 | case WatcherChangeTypes.Changed: 458 | OnChanged(de.Args); 459 | break; 460 | case WatcherChangeTypes.Created: 461 | OnCreated(de.Args); 462 | break; 463 | case WatcherChangeTypes.Deleted: 464 | OnDeleted(de.Args); 465 | break; 466 | case WatcherChangeTypes.Renamed: 467 | OnRenamed(de.Args as RenamedEventArgs); 468 | break; 469 | } 470 | } 471 | } 472 | } 473 | #endregion 474 | } 475 | 476 | /// 477 | /// This class wraps FileSystemEventArgs and RenamedEventArgs objects and detection of duplicate events. 478 | /// 479 | public class DelayedEvent 480 | { 481 | private readonly FileSystemEventArgs _args; 482 | 483 | /// 484 | /// Only delayed events that are unique will be fired. 485 | /// 486 | private bool _delayed; 487 | 488 | 489 | public DelayedEvent(FileSystemEventArgs args) 490 | { 491 | _delayed = false; 492 | _args = args; 493 | } 494 | 495 | public FileSystemEventArgs Args 496 | { 497 | get 498 | { 499 | return _args; 500 | } 501 | } 502 | 503 | public bool Delayed 504 | { 505 | get 506 | { 507 | return _delayed; 508 | } 509 | set 510 | { 511 | _delayed = value; 512 | } 513 | } 514 | 515 | public virtual bool IsDuplicate(object obj) 516 | { 517 | DelayedEvent delayedEvent = obj as DelayedEvent; 518 | if (delayedEvent == null) 519 | return false; // this is not null so they are different 520 | FileSystemEventArgs eO1 = _args; 521 | RenamedEventArgs reO1 = _args as RenamedEventArgs; 522 | FileSystemEventArgs eO2 = delayedEvent._args; 523 | RenamedEventArgs reO2 = delayedEvent._args as RenamedEventArgs; 524 | // The events are equal only if they are of the same type (reO1 and reO2 525 | // are both null or NOT NULL) and have all properties equal. 526 | // We also eliminate Changed events that follow recent Created events 527 | // because many apps create new files by creating an empty file and then 528 | // they update the file with the file content. 529 | return ((eO1 != null && eO2 != null && eO1.ChangeType == eO2.ChangeType 530 | && eO1.FullPath == eO2.FullPath && eO1.Name == eO2.Name) && 531 | ((reO1 == null && reO2 == null) || (reO1 != null && reO2 != null && 532 | reO1.OldFullPath == reO2.OldFullPath && reO1.OldName == reO2.OldName))) || 533 | (eO1 != null && eO2 != null && eO1.ChangeType == WatcherChangeTypes.Created 534 | && eO2.ChangeType == WatcherChangeTypes.Changed 535 | && eO1.FullPath == eO2.FullPath && eO1.Name == eO2.Name); 536 | } 537 | } 538 | 539 | } 540 | -------------------------------------------------------------------------------- /dev/DevelopingConsoleApp/Program.cs: -------------------------------------------------------------------------------- 1 | // See https://aka.ms/new-console-template for more information 2 | using System.Reflection; 3 | using Menelabs; 4 | 5 | FileSystemSafeWatcher safeWatcher = new FileSystemSafeWatcher("C:\\temp"); 6 | safeWatcher.Filters.Add("*.txt"); 7 | safeWatcher.Filters.Add("*.csv"); --------------------------------------------------------------------------------