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
|
//
// System.IO.FileSystemWatcher.cs
//
// Authors:
// Tim Coleman (tim@timcoleman.com)
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// Copyright (C) Tim Coleman, 2002
// (c) 2003 Ximian, Inc. (http://www.ximian.com)
// Copyright (C) 2004, 2006 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO {
[DefaultEvent("Changed")]
[IODescription ("")]
public partial class FileSystemWatcher : Component, ISupportInitialize {
#region Fields
bool inited;
bool start_requested;
bool enableRaisingEvents;
string filter;
bool includeSubdirectories;
int internalBufferSize;
NotifyFilters notifyFilter;
string path;
string fullpath;
ISynchronizeInvoke synchronizingObject;
WaitForChangedResult lastData;
bool waiting;
SearchPattern2 pattern;
bool disposed;
string mangledFilter;
IFileWatcher watcher;
object watcher_handle;
static object lockobj = new object ();
#endregion // Fields
#region Constructors
public FileSystemWatcher ()
{
this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
this.enableRaisingEvents = false;
this.filter = "*";
this.includeSubdirectories = false;
this.internalBufferSize = 8192;
this.path = "";
InitWatcher ();
}
public FileSystemWatcher (string path)
: this (path, "*")
{
}
public FileSystemWatcher (string path, string filter)
{
if (path == null)
throw new ArgumentNullException ("path");
if (filter == null)
throw new ArgumentNullException ("filter");
if (path == String.Empty)
throw new ArgumentException ("Empty path", "path");
if (!Directory.Exists (path))
throw new ArgumentException ("Directory does not exist", "path");
this.inited = false;
this.start_requested = false;
this.enableRaisingEvents = false;
this.filter = filter;
if (this.filter == "*.*")
this.filter = "*";
this.includeSubdirectories = false;
this.internalBufferSize = 8192;
this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
this.path = path;
this.synchronizingObject = null;
InitWatcher ();
}
[EnvironmentPermission (SecurityAction.Assert, Read="MONO_MANAGED_WATCHER")]
void InitWatcher ()
{
lock (lockobj) {
if (watcher_handle != null)
return;
string managed = Environment.GetEnvironmentVariable ("MONO_MANAGED_WATCHER");
int mode = 0;
if (managed == null)
mode = InternalSupportsFSW ();
bool ok = false;
switch (mode) {
case 1: // windows
ok = DefaultWatcher.GetInstance (out watcher);
watcher_handle = this;
break;
case 2: // libfam
ok = FAMWatcher.GetInstance (out watcher, false);
watcher_handle = this;
break;
case 3: // kevent
ok = KeventWatcher.GetInstance (out watcher);
watcher_handle = this;
break;
case 4: // libgamin
ok = FAMWatcher.GetInstance (out watcher, true);
watcher_handle = this;
break;
case 6: // CoreFX
ok = CoreFXFileSystemWatcherProxy.GetInstance (out watcher);
watcher_handle = (watcher as CoreFXFileSystemWatcherProxy).NewWatcher (this);
break;
}
if (mode == 0 || !ok) {
if (String.Compare (managed, "disabled", true) == 0)
NullFileWatcher.GetInstance (out watcher);
else {
DefaultWatcher.GetInstance (out watcher);
watcher_handle = this;
}
}
this.inited = true;
ShowWatcherInfo ();
}
}
[Conditional ("DEBUG"), Conditional ("TRACE")]
void ShowWatcherInfo ()
{
Console.WriteLine ("Watcher implementation: {0}", watcher != null ? watcher.GetType ().ToString () : "<none>");
}
#endregion // Constructors
#region Properties
/* If this is enabled, we Pulse this instance */
internal bool Waiting {
get { return waiting; }
set { waiting = value; }
}
internal string MangledFilter {
get {
if (filter != "*.*")
return filter;
if (mangledFilter != null)
return mangledFilter;
string filterLocal = "*.*";
return filterLocal;
}
}
internal SearchPattern2 Pattern {
get {
if (pattern == null) {
if (watcher?.GetType () == typeof (KeventWatcher))
pattern = new SearchPattern2 (MangledFilter, true); //assume we want to ignore case (OS X)
else
pattern = new SearchPattern2 (MangledFilter);
}
return pattern;
}
}
internal string FullPath {
get {
if (fullpath == null) {
if (path == null || path == "")
fullpath = Environment.CurrentDirectory;
else
fullpath = System.IO.Path.GetFullPath (path);
}
return fullpath;
}
}
[DefaultValue(false)]
[IODescription("Flag to indicate if this instance is active")]
public bool EnableRaisingEvents {
get { return enableRaisingEvents; }
set {
if (disposed)
throw new ObjectDisposedException (GetType().Name);
start_requested = true;
if (!inited)
return;
if (value == enableRaisingEvents)
return; // Do nothing
enableRaisingEvents = value;
if (value) {
Start ();
} else {
Stop ();
start_requested = false;
}
}
}
[DefaultValue("*.*")]
[IODescription("File name filter pattern")]
[SettingsBindable(true)]
[TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
public string Filter {
get { return filter; }
set {
if (value == null || value == "")
value = "*";
if (!string.Equals(filter, value, PathInternal.StringComparison)) {
filter = value == "*.*" ? "*" : value;
pattern = null;
mangledFilter = null;
}
}
}
[DefaultValue(false)]
[IODescription("Flag to indicate we want to watch subdirectories")]
public bool IncludeSubdirectories {
get { return includeSubdirectories; }
set {
if (includeSubdirectories == value)
return;
includeSubdirectories = value;
if (value && enableRaisingEvents) {
Stop ();
Start ();
}
}
}
[Browsable(false)]
[DefaultValue(8192)]
public int InternalBufferSize {
get { return internalBufferSize; }
set {
if (internalBufferSize == value)
return;
if (value < 4096)
value = 4096;
internalBufferSize = value;
if (enableRaisingEvents) {
Stop ();
Start ();
}
}
}
[DefaultValue(NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite)]
[IODescription("Flag to indicate which change event we want to monitor")]
public NotifyFilters NotifyFilter {
get { return notifyFilter; }
set {
if (notifyFilter == value)
return;
notifyFilter = value;
if (enableRaisingEvents) {
Stop ();
Start ();
}
}
}
[DefaultValue("")]
[IODescription("The directory to monitor")]
[SettingsBindable(true)]
[TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
[Editor ("System.Diagnostics.Design.FSWPathEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
public string Path {
get { return path; }
set {
if (disposed)
throw new ObjectDisposedException (GetType().Name);
value = (value == null) ? string.Empty : value;
if (string.Equals(path, value, PathInternal.StringComparison))
return;
bool exists = false;
Exception exc = null;
try {
exists = Directory.Exists (value);
} catch (Exception e) {
exc = e;
}
if (exc != null)
throw new ArgumentException(SR.Format(SR.InvalidDirName, value), nameof(Path));
if (!exists)
throw new ArgumentException(SR.Format(SR.InvalidDirName_NotExists, value), nameof(Path));
path = value;
fullpath = null;
if (enableRaisingEvents) {
Stop ();
Start ();
}
}
}
[Browsable(false)]
public override ISite Site {
get { return base.Site; }
set
{
base.Site = value;
if (Site != null && Site.DesignMode)
this.EnableRaisingEvents = true;
}
}
[DefaultValue(null)]
[IODescription("The object used to marshal the event handler calls resulting from a directory change")]
[Browsable (false)]
public ISynchronizeInvoke SynchronizingObject {
get { return synchronizingObject; }
set { synchronizingObject = value; }
}
#endregion // Properties
#region Methods
public void BeginInit ()
{
// Not necessary in Mono
// but if called, EndInit() must be called
inited = false;
}
protected override void Dispose (bool disposing)
{
if (disposed)
return;
try {
watcher?.StopDispatching (watcher_handle);
watcher?.Dispose (watcher_handle);
} catch (Exception) { }
watcher_handle = null;
watcher = null;
disposed = true;
base.Dispose (disposing);
GC.SuppressFinalize (this);
}
~FileSystemWatcher ()
{
if (disposed)
return;
Dispose (false);
}
public void EndInit ()
{
inited = true;
if (start_requested)
this.EnableRaisingEvents = true;
}
enum EventType {
FileSystemEvent,
ErrorEvent,
RenameEvent
}
private void RaiseEvent (Delegate ev, EventArgs arg, EventType evtype)
{
if (disposed)
return;
if (ev == null)
return;
if (synchronizingObject == null) {
foreach (var target in ev.GetInvocationList()) {
switch (evtype) {
case EventType.RenameEvent:
((RenamedEventHandler)target).Invoke (this, (RenamedEventArgs)arg);
break;
case EventType.ErrorEvent:
((ErrorEventHandler)target).Invoke (this, (ErrorEventArgs)arg);
break;
case EventType.FileSystemEvent:
((FileSystemEventHandler)target).Invoke (this, (FileSystemEventArgs)arg);
break;
}
}
return;
}
synchronizingObject.BeginInvoke (ev, new object [] {this, arg});
}
protected void OnChanged (FileSystemEventArgs e)
{
RaiseEvent (Changed, e, EventType.FileSystemEvent);
}
protected void OnCreated (FileSystemEventArgs e)
{
RaiseEvent (Created, e, EventType.FileSystemEvent);
}
protected void OnDeleted (FileSystemEventArgs e)
{
RaiseEvent (Deleted, e, EventType.FileSystemEvent);
}
protected void OnError (ErrorEventArgs e)
{
RaiseEvent (Error, e, EventType.ErrorEvent);
}
protected void OnRenamed (RenamedEventArgs e)
{
RaiseEvent (Renamed, e, EventType.RenameEvent);
}
public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType)
{
return WaitForChanged (changeType, Timeout.Infinite);
}
public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType, int timeout)
{
WaitForChangedResult result = new WaitForChangedResult ();
bool prevEnabled = EnableRaisingEvents;
if (!prevEnabled)
EnableRaisingEvents = true;
bool gotData;
lock (this) {
waiting = true;
gotData = Monitor.Wait (this, timeout);
if (gotData)
result = this.lastData;
}
EnableRaisingEvents = prevEnabled;
if (!gotData)
result.TimedOut = true;
return result;
}
internal void DispatchErrorEvents (ErrorEventArgs args)
{
if (disposed)
return;
OnError (args);
}
internal void DispatchEvents (FileAction act, string filename, ref RenamedEventArgs renamed)
{
if (disposed)
return;
if (waiting) {
lastData = new WaitForChangedResult ();
}
switch (act) {
case FileAction.Added:
lastData.Name = filename;
lastData.ChangeType = WatcherChangeTypes.Created;
Task.Run (() => OnCreated (new FileSystemEventArgs (WatcherChangeTypes.Created, path, filename)));
break;
case FileAction.Removed:
lastData.Name = filename;
lastData.ChangeType = WatcherChangeTypes.Deleted;
Task.Run (() => OnDeleted (new FileSystemEventArgs (WatcherChangeTypes.Deleted, path, filename)));
break;
case FileAction.Modified:
lastData.Name = filename;
lastData.ChangeType = WatcherChangeTypes.Changed;
Task.Run (() => OnChanged (new FileSystemEventArgs (WatcherChangeTypes.Changed, path, filename)));
break;
case FileAction.RenamedOldName:
if (renamed != null) {
OnRenamed (renamed);
}
lastData.OldName = filename;
lastData.ChangeType = WatcherChangeTypes.Renamed;
renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, filename, "");
break;
case FileAction.RenamedNewName:
lastData.Name = filename;
lastData.ChangeType = WatcherChangeTypes.Renamed;
if (renamed == null) {
renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, "", filename);
}
var renamed_ref = renamed;
Task.Run (() => OnRenamed (renamed_ref));
renamed = null;
break;
default:
break;
}
}
void Start ()
{
if (disposed)
return;
if (watcher_handle == null)
return;
watcher?.StartDispatching (watcher_handle);
}
void Stop ()
{
if (disposed)
return;
if (watcher_handle == null)
return;
watcher?.StopDispatching (watcher_handle);
}
#endregion // Methods
#region Events and Delegates
[IODescription("Occurs when a file/directory change matches the filter")]
public event FileSystemEventHandler Changed;
[IODescription("Occurs when a file/directory creation matches the filter")]
public event FileSystemEventHandler Created;
[IODescription("Occurs when a file/directory deletion matches the filter")]
public event FileSystemEventHandler Deleted;
[Browsable(false)]
public event ErrorEventHandler Error;
[IODescription("Occurs when a file/directory rename matches the filter")]
public event RenamedEventHandler Renamed;
#endregion // Events and Delegates
/* 0 -> not supported */
/* 1 -> windows */
/* 2 -> FAM */
/* 3 -> Kevent */
/* 4 -> gamin */
/* 5 -> inotify */
/* 6 -> CoreFX */
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern int InternalSupportsFSW ();
}
}
|