Ejemplo n.º 1
0
        private static IDisposable SetWatcher(string directory, DirectoryChanged callback)
        {
            var watcher = Get(directory);

            void OnCreated(object sender, FileSystemEventArgs e)
            {
                var local = FileUtils.GetPathWithin(e.FullPath, directory);

                if (local == string.Empty)
                {
                    callback(null);
                }
                else if (local != null)
                {
                    callback(e.FullPath);
                }
            }

            void OnChanged(object sender, FileSystemEventArgs e)
            {
                var local = FileUtils.GetPathWithin(e.FullPath, directory);

                if (!string.IsNullOrEmpty(local))
                {
                    callback(e.FullPath);
                }
            }

            void OnDeleted(object sender, FileSystemEventArgs e)
            {
                var local = FileUtils.GetPathWithin(e.FullPath, directory);

                if (local == string.Empty)
                {
                    callback(null);
                }
                else if (local != null)
                {
                    callback(e.FullPath);
                }
            }

            void OnRenamed(object sender, RenamedEventArgs e)
            {
                var localOld = FileUtils.GetPathWithin(e.OldFullPath, directory);
                var localNew = FileUtils.GetPathWithin(e.FullPath, directory);

                if (localOld == string.Empty || localNew == string.Empty)
                {
                    callback(null);
                }
                else
                {
                    if (localNew != null)
                    {
                        callback(e.FullPath);
                    }
                    if (localOld != null)
                    {
                        callback(e.OldFullPath);
                    }
                }
            }

            watcher.Created += OnCreated;
            watcher.Changed += OnChanged;
            watcher.Deleted += OnDeleted;
            watcher.Renamed += OnRenamed;

            return(new Holder <IDisposable>(watcher, d => {
                var w = (FileSystemWatcher)d;
                w.Created -= OnCreated;
                w.Changed -= OnChanged;
                w.Deleted -= OnDeleted;
                w.Renamed -= OnRenamed;
                Release(w);
            }));
        }