Exemplo n.º 1
0
    private static void WatchFile(string path, NNode <PathInfo> node, NTree <PathInfo> tree)
    {
        FileSystemWatcher watcher = new FileSystemWatcher();

        watcher.Path = path;

        /* Watch for changes in LastAccess and LastWrite times, and
         * the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                               | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.CreationTime;
        // Watch all files.
        watcher.Filter = "";
        watcher.IncludeSubdirectories = false;
        // Add event handlers.
        watcher.Changed += (o, e) =>
        {
            Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
        };
        ///TODO: Invalidate the size with a tag
        watcher.Created += (o, e) =>
        {
            node.AddChild(new NNode <PathInfo> {
                Value = new PathInfo {
                    Path = e.FullPath, IsFile = FastFileOperations.IsFile(e.FullPath), Size = 0
                }
            });
            Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
        };
        watcher.Deleted += (o, e) =>
        {
            var effectedNode = node.Children.FirstOrDefault(p => p.Value.Path == e.FullPath);
            if (effectedNode == null)
            {
                Console.Error.WriteLine("Unexpected error: Cannot find {0} in file tree.", e.FullPath);
            }
            else
            {
                Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
                tree.RemoveNode(effectedNode);
            }
        };

        watcher.Renamed += (o, e) =>
        {
            // Specify what is done when a file is renamed.
            Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
            var effectedNode = node.Children.FirstOrDefault(p => p.Value.Path == e.OldFullPath);
            if (effectedNode == null)
            {
                Console.Error.WriteLine("Unexpected error: Cannot find {0} in file tree.", e.FullPath);
            }
            else
            {
                effectedNode.Value.Path = e.FullPath;
            }
        };

        watcher.Error += watcher_Error;

        // Begin watching.
        watcher.EnableRaisingEvents = true;
    }