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 ();
120 ok = DefaultWatcher.GetInstance (out watcher);
121 //ok = WindowsWatcher.GetInstance (out watcher);
124 ok = FAMWatcher.GetInstance (out watcher, false);
127 ok = KeventWatcher.GetInstance (out watcher);
130 ok = FAMWatcher.GetInstance (out watcher, true);
134 if (mode == 0 || !ok)
135 DefaultWatcher.GetInstance (out watcher);
139 #endregion // Constructors
143 /* If this is enabled, we Pulse this instance */
144 internal bool Waiting {
145 get { return waiting; }
146 set { waiting = value; }
149 internal string MangledFilter {
154 if (mangledFilter != null)
155 return mangledFilter;
157 string filterLocal = "*.*";
158 if (!(watcher.GetType () == typeof (WindowsWatcher)))
165 internal SearchPattern2 Pattern {
167 if (pattern == null) {
168 pattern = new SearchPattern2 (MangledFilter);
174 internal string FullPath {
176 if (fullpath == null) {
177 if (path == null || path == "")
178 fullpath = Environment.CurrentDirectory;
180 fullpath = System.IO.Path.GetFullPath (path);
187 [DefaultValue(false)]
188 [IODescription("Flag to indicate if this instance is active")]
189 public bool EnableRaisingEvents {
190 get { return enableRaisingEvents; }
192 if (value == enableRaisingEvents)
193 return; // Do nothing
195 enableRaisingEvents = value;
204 [DefaultValue("*.*")]
205 [IODescription("File name filter pattern")]
206 [RecommendedAsConfigurable(true)]
207 [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
208 public string Filter {
209 get { return filter; }
211 if (value == null || value == "")
214 if (filter != value) {
217 mangledFilter = null;
222 [DefaultValue(false)]
223 [IODescription("Flag to indicate we want to watch subdirectories")]
224 public bool IncludeSubdirectories {
225 get { return includeSubdirectories; }
227 if (includeSubdirectories == value)
230 includeSubdirectories = value;
231 if (value && enableRaisingEvents) {
240 public int InternalBufferSize {
241 get { return internalBufferSize; }
243 if (internalBufferSize == value)
249 internalBufferSize = value;
250 if (enableRaisingEvents) {
257 [DefaultValue(NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite)]
258 [IODescription("Flag to indicate which change event we want to monitor")]
259 public NotifyFilters NotifyFilter {
260 get { return notifyFilter; }
262 if (notifyFilter == value)
265 notifyFilter = value;
266 if (enableRaisingEvents) {
274 [IODescription("The directory to monitor")]
275 [RecommendedAsConfigurable(true)]
276 [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
277 [Editor ("System.Diagnostics.Design.FSWPathEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
285 Exception exc = null;
288 exists = Directory.Exists (value);
289 } catch (Exception e) {
294 throw new ArgumentException ("Invalid directory name", "value", exc);
297 throw new ArgumentException ("Directory does not exists", "value");
301 if (enableRaisingEvents) {
309 public override ISite Site {
310 get { return base.Site; }
311 set { base.Site = value; }
315 [IODescription("The object used to marshal the event handler calls resulting from a directory change")]
316 public ISynchronizeInvoke SynchronizingObject {
317 get { return synchronizingObject; }
318 set { synchronizingObject = value; }
321 #endregion // Properties
326 public void BeginInit ()
328 throw new NotImplementedException ();
331 protected override void Dispose (bool disposing)
338 base.Dispose (disposing);
341 ~FileSystemWatcher ()
348 public void EndInit ()
350 throw new NotImplementedException ();
353 private void RaiseEvent (Delegate ev, EventArgs arg)
358 object [] args = new object [] {this, arg};
360 if (synchronizingObject == null) {
361 ev.DynamicInvoke (args);
365 synchronizingObject.BeginInvoke (ev, args);
368 protected void OnChanged (FileSystemEventArgs e)
370 RaiseEvent (Changed, e);
373 protected void OnCreated (FileSystemEventArgs e)
375 RaiseEvent (Created, e);
378 protected void OnDeleted (FileSystemEventArgs e)
380 RaiseEvent (Deleted, e);
383 protected void OnError (ErrorEventArgs e)
385 RaiseEvent (Error, e);
388 protected void OnRenamed (RenamedEventArgs e)
390 RaiseEvent (Renamed, e);
393 public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType)
395 return WaitForChanged (changeType, Timeout.Infinite);
398 public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType, int timeout)
400 WaitForChangedResult result = new WaitForChangedResult ();
401 bool prevEnabled = EnableRaisingEvents;
403 EnableRaisingEvents = true;
408 gotData = Monitor.Wait (this, timeout);
410 result = this.lastData;
413 EnableRaisingEvents = prevEnabled;
415 result.TimedOut = true;
420 internal void DispatchEvents (FileAction act, string filename, ref RenamedEventArgs renamed)
423 lastData = new WaitForChangedResult ();
427 case FileAction.Added:
428 lastData.Name = filename;
429 lastData.ChangeType = WatcherChangeTypes.Created;
430 OnCreated (new FileSystemEventArgs (WatcherChangeTypes.Created, path, filename));
432 case FileAction.Removed:
433 lastData.Name = filename;
434 lastData.ChangeType = WatcherChangeTypes.Deleted;
435 OnDeleted (new FileSystemEventArgs (WatcherChangeTypes.Deleted, path, filename));
437 case FileAction.Modified:
438 lastData.Name = filename;
439 lastData.ChangeType = WatcherChangeTypes.Changed;
440 OnChanged (new FileSystemEventArgs (WatcherChangeTypes.Changed, path, filename));
442 case FileAction.RenamedOldName:
443 if (renamed != null) {
446 lastData.OldName = filename;
447 lastData.ChangeType = WatcherChangeTypes.Renamed;
448 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, null, filename);
450 case FileAction.RenamedNewName:
451 lastData.Name = filename;
452 lastData.ChangeType = WatcherChangeTypes.Renamed;
453 if (renamed != null) {
454 renamed.SetName (filename);
456 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, filename, null);
468 watcher.StartDispatching (this);
473 watcher.StopDispatching (this);
475 #endregion // Methods
477 #region Events and Delegates
479 [IODescription("Occurs when a file/directory change matches the filter")]
480 public event FileSystemEventHandler Changed;
482 [IODescription("Occurs when a file/directory creation matches the filter")]
483 public event FileSystemEventHandler Created;
485 [IODescription("Occurs when a file/directory deletion matches the filter")]
486 public event FileSystemEventHandler Deleted;
489 public event ErrorEventHandler Error;
491 [IODescription("Occurs when a file/directory rename matches the filter")]
492 public event RenamedEventHandler Renamed;
494 #endregion // Events and Delegates
496 /* 0 -> not supported */
499 [MethodImplAttribute(MethodImplOptions.InternalCall)]
500 static extern int InternalSupportsFSW ();
502 /*[MethodImplAttribute(MethodImplOptions.InternalCall)]
503 static extern IntPtr InternalOpenDirectory (string path, IntPtr reserved);
505 [MethodImplAttribute(MethodImplOptions.InternalCall)]
506 static extern IntPtr InternalCloseDirectory (IntPtr handle);
508 [MethodImplAttribute(MethodImplOptions.InternalCall)]
509 static extern bool InternalReadDirectoryChanges (IntPtr handle,
511 bool includeSubdirectories,
512 NotifyFilters notifyFilter,
513 out NativeOverlapped overlap,
514 OverlappedHandler overlappedCallback);