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);
133 ok = InotifyWatcher.GetInstance (out watcher, true);
137 if (mode == 0 || !ok)
138 DefaultWatcher.GetInstance (out watcher);
142 #endregion // Constructors
146 /* If this is enabled, we Pulse this instance */
147 internal bool Waiting {
148 get { return waiting; }
149 set { waiting = value; }
152 internal string MangledFilter {
157 if (mangledFilter != null)
158 return mangledFilter;
160 string filterLocal = "*.*";
161 if (!(watcher.GetType () == typeof (WindowsWatcher)))
168 internal SearchPattern2 Pattern {
170 if (pattern == null) {
171 pattern = new SearchPattern2 (MangledFilter);
177 internal string FullPath {
179 if (fullpath == null) {
180 if (path == null || path == "")
181 fullpath = Environment.CurrentDirectory;
183 fullpath = System.IO.Path.GetFullPath (path);
190 [DefaultValue(false)]
191 [IODescription("Flag to indicate if this instance is active")]
192 public bool EnableRaisingEvents {
193 get { return enableRaisingEvents; }
195 if (value == enableRaisingEvents)
196 return; // Do nothing
198 enableRaisingEvents = value;
207 [DefaultValue("*.*")]
208 [IODescription("File name filter pattern")]
209 [RecommendedAsConfigurable(true)]
210 [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
211 public string Filter {
212 get { return filter; }
214 if (value == null || value == "")
217 if (filter != value) {
220 mangledFilter = null;
225 [DefaultValue(false)]
226 [IODescription("Flag to indicate we want to watch subdirectories")]
227 public bool IncludeSubdirectories {
228 get { return includeSubdirectories; }
230 if (includeSubdirectories == value)
233 includeSubdirectories = value;
234 if (value && enableRaisingEvents) {
243 public int InternalBufferSize {
244 get { return internalBufferSize; }
246 if (internalBufferSize == value)
252 internalBufferSize = value;
253 if (enableRaisingEvents) {
260 [DefaultValue(NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite)]
261 [IODescription("Flag to indicate which change event we want to monitor")]
262 public NotifyFilters NotifyFilter {
263 get { return notifyFilter; }
265 if (notifyFilter == value)
268 notifyFilter = value;
269 if (enableRaisingEvents) {
277 [IODescription("The directory to monitor")]
278 [RecommendedAsConfigurable(true)]
279 [TypeConverter ("System.Diagnostics.Design.StringValueConverter, " + Consts.AssemblySystem_Design)]
280 [Editor ("System.Diagnostics.Design.FSWPathEditor, " + Consts.AssemblySystem_Design, "System.Drawing.Design.UITypeEditor, " + Consts.AssemblySystem_Drawing)]
288 Exception exc = null;
291 exists = Directory.Exists (value);
292 } catch (Exception e) {
297 throw new ArgumentException ("Invalid directory name", "value", exc);
300 throw new ArgumentException ("Directory does not exists", "value");
304 if (enableRaisingEvents) {
312 public override ISite Site {
313 get { return base.Site; }
314 set { base.Site = value; }
318 [IODescription("The object used to marshal the event handler calls resulting from a directory change")]
319 public ISynchronizeInvoke SynchronizingObject {
320 get { return synchronizingObject; }
321 set { synchronizingObject = value; }
324 #endregion // Properties
329 public void BeginInit ()
331 throw new NotImplementedException ();
334 protected override void Dispose (bool disposing)
341 base.Dispose (disposing);
344 ~FileSystemWatcher ()
351 public void EndInit ()
353 throw new NotImplementedException ();
356 private void RaiseEvent (Delegate ev, EventArgs arg)
361 object [] args = new object [] {this, arg};
363 if (synchronizingObject == null) {
364 ev.DynamicInvoke (args);
368 synchronizingObject.BeginInvoke (ev, args);
371 protected void OnChanged (FileSystemEventArgs e)
373 RaiseEvent (Changed, e);
376 protected void OnCreated (FileSystemEventArgs e)
378 RaiseEvent (Created, e);
381 protected void OnDeleted (FileSystemEventArgs e)
383 RaiseEvent (Deleted, e);
386 protected void OnError (ErrorEventArgs e)
388 RaiseEvent (Error, e);
391 protected void OnRenamed (RenamedEventArgs e)
393 RaiseEvent (Renamed, e);
396 public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType)
398 return WaitForChanged (changeType, Timeout.Infinite);
401 public WaitForChangedResult WaitForChanged (WatcherChangeTypes changeType, int timeout)
403 WaitForChangedResult result = new WaitForChangedResult ();
404 bool prevEnabled = EnableRaisingEvents;
406 EnableRaisingEvents = true;
411 gotData = Monitor.Wait (this, timeout);
413 result = this.lastData;
416 EnableRaisingEvents = prevEnabled;
418 result.TimedOut = true;
423 internal void DispatchEvents (FileAction act, string filename, ref RenamedEventArgs renamed)
426 lastData = new WaitForChangedResult ();
430 case FileAction.Added:
431 lastData.Name = filename;
432 lastData.ChangeType = WatcherChangeTypes.Created;
433 OnCreated (new FileSystemEventArgs (WatcherChangeTypes.Created, path, filename));
435 case FileAction.Removed:
436 lastData.Name = filename;
437 lastData.ChangeType = WatcherChangeTypes.Deleted;
438 OnDeleted (new FileSystemEventArgs (WatcherChangeTypes.Deleted, path, filename));
440 case FileAction.Modified:
441 lastData.Name = filename;
442 lastData.ChangeType = WatcherChangeTypes.Changed;
443 OnChanged (new FileSystemEventArgs (WatcherChangeTypes.Changed, path, filename));
445 case FileAction.RenamedOldName:
446 if (renamed != null) {
449 lastData.OldName = filename;
450 lastData.ChangeType = WatcherChangeTypes.Renamed;
451 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, null, filename);
453 case FileAction.RenamedNewName:
454 lastData.Name = filename;
455 lastData.ChangeType = WatcherChangeTypes.Renamed;
456 if (renamed != null) {
457 renamed.SetName (filename);
459 renamed = new RenamedEventArgs (WatcherChangeTypes.Renamed, path, filename, null);
471 watcher.StartDispatching (this);
476 watcher.StopDispatching (this);
478 #endregion // Methods
480 #region Events and Delegates
482 [IODescription("Occurs when a file/directory change matches the filter")]
483 public event FileSystemEventHandler Changed;
485 [IODescription("Occurs when a file/directory creation matches the filter")]
486 public event FileSystemEventHandler Created;
488 [IODescription("Occurs when a file/directory deletion matches the filter")]
489 public event FileSystemEventHandler Deleted;
492 public event ErrorEventHandler Error;
494 [IODescription("Occurs when a file/directory rename matches the filter")]
495 public event RenamedEventHandler Renamed;
497 #endregion // Events and Delegates
499 /* 0 -> not supported */
505 [MethodImplAttribute(MethodImplOptions.InternalCall)]
506 static extern int InternalSupportsFSW ();