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 // (c) 2004 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.
35 using System.ComponentModel;
36 using System.Runtime.CompilerServices;
37 using System.Runtime.InteropServices;
38 using System.Threading;
41 [DefaultEvent("Changed")]
42 public class FileSystemWatcher : Component, ISupportInitialize {
46 bool enableRaisingEvents;
48 bool includeSubdirectories;
49 int internalBufferSize;
50 NotifyFilters notifyFilter;
53 ISynchronizeInvoke synchronizingObject;
54 WaitForChangedResult lastData;
56 SearchPattern2 pattern;
59 static IFileWatcher watcher;
60 static object lockobj = new object ();
66 public FileSystemWatcher ()
68 this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
69 this.enableRaisingEvents = false;
71 this.includeSubdirectories = false;
72 this.internalBufferSize = 8192;
77 public FileSystemWatcher (string path)
82 public FileSystemWatcher (string path, string filter)
85 throw new ArgumentNullException ("path");
88 throw new ArgumentNullException ("filter");
90 if (path == String.Empty)
91 throw new ArgumentException ("Empty path", "path");
93 if (!Directory.Exists (path))
94 throw new ArgumentException ("Directory does not exists", "path");
96 this.enableRaisingEvents = false;
98 this.includeSubdirectories = false;
99 this.internalBufferSize = 8192;
100 this.notifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
102 this.synchronizingObject = null;
112 string managed = Environment.GetEnvironmentVariable ("MONO_MANAGED_WATCHER");
115 mode = InternalSupportsFSW ();
119 ok = KeventWatcher.GetInstance (out watcher);
121 ok = FAMWatcher.GetInstance (out watcher);
123 ok = DefaultWatcher.GetInstance (out watcher);
124 //ok = WindowsWatcher.GetInstance (out watcher);
126 if (mode == 0 || !ok)
127 DefaultWatcher.GetInstance (out watcher);
131 #endregion // Constructors
135 /* If this is enabled, we Pulse this instance */
136 internal bool Waiting {
137 get { return waiting; }
138 set { waiting = value; }
141 internal string MangledFilter {
146 if (mangledFilter != null)
147 return mangledFilter;
149 string filterLocal = "*.*";
150 if (!(watcher.GetType () == typeof (WindowsWatcher)))
157 internal SearchPattern2 Pattern {
159 if (pattern == null) {
160 pattern = new SearchPattern2 (MangledFilter);
166 internal string FullPath {
168 if (fullpath == null) {
169 if (path == null || path == "")
170 fullpath = Environment.CurrentDirectory;
172 fullpath = System.IO.Path.GetFullPath (path);
179 [DefaultValue(false)]
180 [IODescription("Flag to indicate if this instance is active")]
181 public bool EnableRaisingEvents {
182 get { return enableRaisingEvents; }
184 if (value == enableRaisingEvents)
185 return; // Do nothing
187 enableRaisingEvents = value;
196 [DefaultValue("*.*")]
197 [IODescription("File name filter pattern")]
198 [RecommendedAsConfigurable(true)]
199 [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
200 public string Filter {
201 get { return filter; }
203 if (value == null || value == "")
206 if (filter != value) {
209 mangledFilter = null;
214 [DefaultValue(false)]
215 [IODescription("Flag to indicate we want to watch subdirectories")]
216 public bool IncludeSubdirectories {
217 get { return includeSubdirectories; }
219 if (includeSubdirectories == value)
222 includeSubdirectories = value;
223 if (value && enableRaisingEvents) {
232 public int InternalBufferSize {
233 get { return internalBufferSize; }
235 if (internalBufferSize == value)
241 internalBufferSize = value;
242 if (enableRaisingEvents) {
249 [DefaultValue(NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite)]
250 [IODescription("Flag to indicate which change event we want to monitor")]
251 public NotifyFilters NotifyFilter {
252 get { return notifyFilter; }
254 if (notifyFilter == value)
257 notifyFilter = value;
258 if (enableRaisingEvents) {
266 [IODescription("The directory to monitor")]
267 [RecommendedAsConfigurable(true)]
268 [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
269 [Editor ("System.Diagnostics.Design.FSWPathEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
277 Exception exc = null;
280 exists = Directory.Exists (value);
281 } catch (Exception e) {
286 throw new ArgumentException ("Invalid directory name", "value", exc);
289 throw new ArgumentException ("Directory does not exists", "value");
293 if (enableRaisingEvents) {
301 public override ISite Site {
302 get { return base.Site; }
303 set { base.Site = value; }
307 [IODescription("The object used to marshal the event handler calls resulting from a directory change")]
308 public ISynchronizeInvoke SynchronizingObject {
309 get { return synchronizingObject; }
310 set { synchronizingObject = value; }
313 #endregion // Properties
318 public void BeginInit ()
320 throw new NotImplementedException ();
323 protected override void Dispose (bool disposing)
330 base.Dispose (disposing);
333 ~FileSystemWatcher ()
340 public void EndInit ()
342 throw new NotImplementedException ();
345 private void RaiseEvent (Delegate ev, EventArgs arg)
350 object [] args = new object [] {this, arg};
352 if (synchronizingObject == null) {
353 ev.DynamicInvoke (args);
357 synchronizingObject.BeginInvoke (ev, args);
360 protected void OnChanged (FileSystemEventArgs e)
362 RaiseEvent (Changed, e);
365 protected void OnCreated (FileSystemEventArgs e)
367 RaiseEvent (Created, e);
370 protected void OnDeleted (FileSystemEventArgs e)
372 RaiseEvent (Deleted, e);
375 protected void OnError (ErrorEventArgs e)
377 RaiseEvent (Error, e);
380 protected void OnRenamed (RenamedEventArgs e)
382 RaiseEvent (Renamed, e);
385 public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType)
387 return WaitForChanged (changeType, Timeout.Infinite);
390 public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType, int timeout)
392 WaitForChangedResult result = new WaitForChangedResult ();
393 bool prevEnabled = EnableRaisingEvents;
395 EnableRaisingEvents = true;
400 gotData = Monitor.Wait (this, timeout);
402 result = this.lastData;
405 EnableRaisingEvents = prevEnabled;
407 result.TimedOut = true;
412 internal void DispatchEvents (FileAction act, string filename, ref RenamedEventArgs renamed)
415 lastData = new WaitForChangedResult ();
419 case FileAction.Added:
420 lastData.Name = filename;
421 lastData.ChangeType = WatcherChangeTypes.Created;
422 OnCreated (new FileSystemEventArgs (WatcherChangeTypes.Created, path, filename));
424 case FileAction.Removed:
425 lastData.Name = filename;
426 lastData.ChangeType = WatcherChangeTypes.Deleted;
427 OnDeleted (new FileSystemEventArgs (WatcherChangeTypes.Deleted, path, filename));
429 case FileAction.Modified:
430 lastData.Name = filename;
431 lastData.ChangeType = WatcherChangeTypes.Changed;
432 OnChanged (new FileSystemEventArgs (WatcherChangeTypes.Changed, path, filename));
434 case FileAction.RenamedOldName:
435 if (renamed != null) {
438 lastData.OldName = filename;
439 lastData.ChangeType = WatcherChangeTypes.Renamed;
440 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, null, filename);
442 case FileAction.RenamedNewName:
443 lastData.Name = filename;
444 lastData.ChangeType = WatcherChangeTypes.Renamed;
445 if (renamed != null) {
446 renamed.SetName (filename);
448 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, filename, null);
460 watcher.StartDispatching (this);
465 watcher.StopDispatching (this);
467 #endregion // Methods
469 #region Events and Delegates
471 [IODescription("Occurs when a file/directory change matches the filter")]
472 public event FileSystemEventHandler Changed;
474 [IODescription("Occurs when a file/directory creation matches the filter")]
475 public event FileSystemEventHandler Created;
477 [IODescription("Occurs when a file/directory deletion matches the filter")]
478 public event FileSystemEventHandler Deleted;
481 public event ErrorEventHandler Error;
483 [IODescription("Occurs when a file/directory rename matches the filter")]
484 public event RenamedEventHandler Renamed;
486 #endregion // Events and Delegates
488 /* 0 -> not supported */
491 [MethodImplAttribute(MethodImplOptions.InternalCall)]
492 static extern int InternalSupportsFSW ();
494 /*[MethodImplAttribute(MethodImplOptions.InternalCall)]
495 static extern IntPtr InternalOpenDirectory (string path, IntPtr reserved);
497 [MethodImplAttribute(MethodImplOptions.InternalCall)]
498 static extern IntPtr InternalCloseDirectory (IntPtr handle);
500 [MethodImplAttribute(MethodImplOptions.InternalCall)]
501 static extern bool InternalReadDirectoryChanges (IntPtr handle,
503 bool includeSubdirectories,
504 NotifyFilters notifyFilter,
505 out NativeOverlapped overlap,
506 OverlappedHandler overlappedCallback);