2 // System.IO.FileSystemWatcher.cs
5 // Tim Coleman (tim@timcoleman.com)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // Copyright (C) Tim Coleman, 2002
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 // Copyright (C) 2004, 2006 Novell, Inc (http://www.novell.com)
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 using System.ComponentModel;
35 using System.Diagnostics;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.InteropServices;
38 using System.Security.Permissions;
39 using System.Threading;
42 [DefaultEvent("Changed")]
44 public class FileSystemWatcher : Component, ISupportInitialize {
48 bool enableRaisingEvents;
50 bool includeSubdirectories;
51 int internalBufferSize;
52 NotifyFilters notifyFilter;
55 ISynchronizeInvoke synchronizingObject;
56 WaitForChangedResult lastData;
58 SearchPattern2 pattern;
61 static IFileWatcher watcher;
62 static object lockobj = new object ();
68 public FileSystemWatcher ()
70 this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
71 this.enableRaisingEvents = false;
73 this.includeSubdirectories = false;
74 this.internalBufferSize = 8192;
79 public FileSystemWatcher (string path)
84 public FileSystemWatcher (string path, string filter)
87 throw new ArgumentNullException ("path");
90 throw new ArgumentNullException ("filter");
92 if (path == String.Empty)
93 throw new ArgumentException ("Empty path", "path");
95 if (!Directory.Exists (path))
96 throw new ArgumentException ("Directory does not exist", "path");
98 this.enableRaisingEvents = false;
100 this.includeSubdirectories = false;
101 this.internalBufferSize = 8192;
102 this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
104 this.synchronizingObject = null;
108 [EnvironmentPermission (SecurityAction.Assert, Read="MONO_MANAGED_WATCHER")]
115 string managed = Environment.GetEnvironmentVariable ("MONO_MANAGED_WATCHER");
118 mode = InternalSupportsFSW ();
123 ok = DefaultWatcher.GetInstance (out watcher);
124 //ok = WindowsWatcher.GetInstance (out watcher);
127 ok = FAMWatcher.GetInstance (out watcher, false);
130 ok = KeventWatcher.GetInstance (out watcher);
133 ok = FAMWatcher.GetInstance (out watcher, true);
136 ok = InotifyWatcher.GetInstance (out watcher, true);
140 if (mode == 0 || !ok) {
141 if (String.Compare (managed, "disabled", true) == 0)
142 NullFileWatcher.GetInstance (out watcher);
144 DefaultWatcher.GetInstance (out watcher);
151 [Conditional ("DEBUG"), Conditional ("TRACE")]
152 void ShowWatcherInfo ()
154 Console.WriteLine ("Watcher implementation: {0}", watcher != null ? watcher.GetType ().ToString () : "<none>");
157 #endregion // Constructors
161 /* If this is enabled, we Pulse this instance */
162 internal bool Waiting {
163 get { return waiting; }
164 set { waiting = value; }
167 internal string MangledFilter {
172 if (mangledFilter != null)
173 return mangledFilter;
175 string filterLocal = "*.*";
176 if (!(watcher.GetType () == typeof (WindowsWatcher)))
183 internal SearchPattern2 Pattern {
185 if (pattern == null) {
186 pattern = new SearchPattern2 (MangledFilter);
192 internal string FullPath {
194 if (fullpath == null) {
195 if (path == null || path == "")
196 fullpath = Environment.CurrentDirectory;
198 fullpath = System.IO.Path.GetFullPath (path);
205 [DefaultValue(false)]
206 [IODescription("Flag to indicate if this instance is active")]
207 public bool EnableRaisingEvents {
208 get { return enableRaisingEvents; }
210 if (value == enableRaisingEvents)
211 return; // Do nothing
213 enableRaisingEvents = value;
222 [DefaultValue("*.*")]
223 [IODescription("File name filter pattern")]
224 [RecommendedAsConfigurable(true)]
225 [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
226 public string Filter {
227 get { return filter; }
229 if (value == null || value == "")
232 if (filter != value) {
235 mangledFilter = null;
240 [DefaultValue(false)]
241 [IODescription("Flag to indicate we want to watch subdirectories")]
242 public bool IncludeSubdirectories {
243 get { return includeSubdirectories; }
245 if (includeSubdirectories == value)
248 includeSubdirectories = value;
249 if (value && enableRaisingEvents) {
258 public int InternalBufferSize {
259 get { return internalBufferSize; }
261 if (internalBufferSize == value)
267 internalBufferSize = value;
268 if (enableRaisingEvents) {
275 [DefaultValue(NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite)]
276 [IODescription("Flag to indicate which change event we want to monitor")]
277 public NotifyFilters NotifyFilter {
278 get { return notifyFilter; }
280 if (notifyFilter == value)
283 notifyFilter = value;
284 if (enableRaisingEvents) {
292 [IODescription("The directory to monitor")]
293 [RecommendedAsConfigurable(true)]
294 [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
295 [Editor ("System.Diagnostics.Design.FSWPathEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
303 Exception exc = null;
306 exists = Directory.Exists (value);
307 } catch (Exception e) {
312 throw new ArgumentException ("Invalid directory name", "value", exc);
315 throw new ArgumentException ("Directory does not exist", "value");
319 if (enableRaisingEvents) {
327 public override ISite Site {
328 get { return base.Site; }
329 set { base.Site = value; }
333 [IODescription("The object used to marshal the event handler calls resulting from a directory change")]
335 public ISynchronizeInvoke SynchronizingObject {
336 get { return synchronizingObject; }
337 set { synchronizingObject = value; }
340 #endregion // Properties
344 public void BeginInit ()
346 // Not necessary in Mono
349 protected override void Dispose (bool disposing)
356 base.Dispose (disposing);
359 ~FileSystemWatcher ()
365 public void EndInit ()
367 // Not necessary in Mono
375 private void RaiseEvent (Delegate ev, EventArgs arg, EventType evtype)
380 if (synchronizingObject == null) {
382 case EventType.RenameEvent:
383 ((RenamedEventHandler)ev).BeginInvoke (this, (RenamedEventArgs) arg, null, null);
385 case EventType.ErrorEvent:
386 ((ErrorEventHandler)ev).BeginInvoke (this, (ErrorEventArgs) arg, null, null);
388 case EventType.FileSystemEvent:
389 ((FileSystemEventHandler)ev).BeginInvoke (this, (FileSystemEventArgs) arg, null, null);
395 synchronizingObject.BeginInvoke (ev, new object [] {this, arg});
398 protected void OnChanged (FileSystemEventArgs e)
400 RaiseEvent (Changed, e, EventType.FileSystemEvent);
403 protected void OnCreated (FileSystemEventArgs e)
405 RaiseEvent (Created, e, EventType.FileSystemEvent);
408 protected void OnDeleted (FileSystemEventArgs e)
410 RaiseEvent (Deleted, e, EventType.FileSystemEvent);
413 protected void OnError (ErrorEventArgs e)
415 RaiseEvent (Error, e, EventType.ErrorEvent);
418 protected void OnRenamed (RenamedEventArgs e)
420 RaiseEvent (Renamed, e, EventType.RenameEvent);
423 public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType)
425 return WaitForChanged (changeType, Timeout.Infinite);
428 public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType, int timeout)
430 WaitForChangedResult result = new WaitForChangedResult ();
431 bool prevEnabled = EnableRaisingEvents;
433 EnableRaisingEvents = true;
438 gotData = Monitor.Wait (this, timeout);
440 result = this.lastData;
443 EnableRaisingEvents = prevEnabled;
445 result.TimedOut = true;
450 internal void DispatchEvents (FileAction act, string filename, ref RenamedEventArgs renamed)
453 lastData = new WaitForChangedResult ();
457 case FileAction.Added:
458 lastData.Name = filename;
459 lastData.ChangeType = WatcherChangeTypes.Created;
460 OnCreated (new FileSystemEventArgs (WatcherChangeTypes.Created, path, filename));
462 case FileAction.Removed:
463 lastData.Name = filename;
464 lastData.ChangeType = WatcherChangeTypes.Deleted;
465 OnDeleted (new FileSystemEventArgs (WatcherChangeTypes.Deleted, path, filename));
467 case FileAction.Modified:
468 lastData.Name = filename;
469 lastData.ChangeType = WatcherChangeTypes.Changed;
470 OnChanged (new FileSystemEventArgs (WatcherChangeTypes.Changed, path, filename));
472 case FileAction.RenamedOldName:
473 if (renamed != null) {
476 lastData.OldName = filename;
477 lastData.ChangeType = WatcherChangeTypes.Renamed;
478 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, filename, "");
480 case FileAction.RenamedNewName:
481 lastData.Name = filename;
482 lastData.ChangeType = WatcherChangeTypes.Renamed;
483 if (renamed == null) {
484 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, "", filename);
496 watcher.StartDispatching (this);
501 watcher.StopDispatching (this);
503 #endregion // Methods
505 #region Events and Delegates
507 [IODescription("Occurs when a file/directory change matches the filter")]
508 public event FileSystemEventHandler Changed;
510 [IODescription("Occurs when a file/directory creation matches the filter")]
511 public event FileSystemEventHandler Created;
513 [IODescription("Occurs when a file/directory deletion matches the filter")]
514 public event FileSystemEventHandler Deleted;
517 public event ErrorEventHandler Error;
519 [IODescription("Occurs when a file/directory rename matches the filter")]
520 public event RenamedEventHandler Renamed;
522 #endregion // Events and Delegates
524 /* 0 -> not supported */
530 [MethodImplAttribute(MethodImplOptions.InternalCall)]
531 static extern int InternalSupportsFSW ();