Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor multiple folders using FileSystemWatcher

Whats the best way to monitor multiple folders (not subdirectories) using FileSystemWatcher in C#?

like image 665
Bi. Avatar asked Apr 26 '10 19:04

Bi.


5 Answers

I don't think FSW supports monitoring multiple folders, so just instantiate one per folder you want to monitor. You can point the event handlers at the same methods, though, which should end up working like I think you want.

like image 163
Factor Mystic Avatar answered Nov 15 '22 04:11

Factor Mystic


The easiest way is to create multiple instances of the FileSystemWatcher object.

http://www.c-sharpcorner.com/UploadFile/mokhtarb2005/FSWatcherMB12052005063103AM/FSWatcherMB.aspx

You'll have to make sure the you handle events between the two folders correctly:

Although some common occurances, such as copying or moving a file, do not correspond directly to an event, these occurances do cause events to be raised. When you copy a file, the system raises a Created event in the directory to which the file was copied but does not raise any events in the original directory. When you move a file, the server raises two events: a Deleted event in the source directory, followed by a Created event in the target directory.

For example, you create two instances of FileSystemWatcher. FileSystemWatcher1 is set to watch "C:\My Documents", and FileSystemWatcher2 is set to watch "C:\Your Documents". Now, if you copy a file from "My Documents" into "Your Documents", a Created event will be raised by FileSystemWatcher2, but no event is raised for FileSystemWatcher1. Unlike copying, moving a file or directory would raise two events. From the previous example, if you moved a file from "My Documents" to "Your Documents", a Created event would be raised by FileSystemWatcher2 and a Deleted event would be raised by FileSystemWatcher

Link to FileSystemEventArgs

like image 26
kemiller2002 Avatar answered Nov 15 '22 03:11

kemiller2002


Out of the box, FileSystemWatcher only supports monitoring a single parent directory. To monitor multiple sibling directories, you would need to create multiple instances of FileSystemWatcher.

You can try cheating this behavior, however, by taking advantage of FileSystemWatcher's ability to include subdirectories. You can create an NTFS junction point (aka symbolic link) as a subdirectory from the directory you are watching. Mark Russinovich of Sysinternals fame has a utility called Junction to simplify creation and management of symlinks.

Note that you can only create symlinks to directories on your local machine.

like image 6
Tim Trout Avatar answered Nov 15 '22 03:11

Tim Trout


Although this is an old question I decided to answer, because I couldn't find a good answer anywhere.

So, the aim was to monitor multiple folders (not subdirectories) using FileSystemWatcher? Here's my suggestion:

using System;
using System.IO;
using System.Security.Permissions;
using System.Collections.Generic;

namespace MultiWatcher
// ConsoleApplication, which monitors TXT-files in multiple folders. 
// Inspired by:
// http://msdn.microsoft.com/en-us/library/system.io.filesystemeventargs(v=vs.100).aspx

{
    public class Watchers
    {
        public static void Main()
        {
            Run();

        }

        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static void Run()
        {
            string[] args = System.Environment.GetCommandLineArgs();

            // If a directory is not specified, exit program.
            if (args.Length < 2)
            {
                // Display the proper way to call the program.
                Console.WriteLine("Usage: Watcher.exe PATH [...] [PATH]";
                return;
            }
            List<string> list = new List<string>();
            for (int i = 1; i < args.Length; i++)
            {
                list.Add(args[i]);
            }
            foreach (string my_path in list)
            {
                Watch(my_path);
            }

            // Wait for the user to quit the program.
            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
        private static void Watch(string watch_folder)
        {
            // Create a new FileSystemWatcher and set its properties.
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = watch_folder;
            /* 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;
            // Only watch text files.
            watcher.Filter = "*.txt";

            // Add event handlers.
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.Deleted += new FileSystemEventHandler(OnChanged);
            watcher.Renamed += new RenamedEventHandler(OnRenamed);

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

        // Define the event handlers.
        private static void OnChanged(object source, FileSystemEventArgs e)
        {
            // Specify what is done when a file is changed, created, or deleted.
            Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
        }

        private static void OnRenamed(object source, RenamedEventArgs e)
        {
            // Specify what is done when a file is renamed.
            Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
        }
    }
}
like image 5
Ciove Avatar answered Nov 15 '22 03:11

Ciove


Can you simply use multiple instances of the FileSystemWatcher, one for each directory?

like image 3
Charlie Salts Avatar answered Nov 15 '22 05:11

Charlie Salts