Search code examples
c#filesystemwatcher

Can I delete a file when I am watching it with a FileSystemWatcher?


We know that in .NET (C# to be specific), we can use a FileSystemWatcher to detect any type of modification.

public void MessageFileWatcher(string Path, string FileName)
        {
            FileSystemWatcher Watcher = new FileSystemWatcher();
            Watcher.Path = Path;
            Watcher.Filter = FileName;
            Watcher.NotifyFilter = NotifyFilters.LastWrite;
            Watcher.Changed += new FileSystemEventHandler(OnChanged);
            Watcher.EnableRaisingEvents = true;
        }

but I want to keep a watch on a file and after some time also want to delete that file.

To be precise. can FileSystemWatcher class always look for modifications... and if I want to delete that particular file, will it raise an exception?


Solution

  • It won't raise an exception.

    A FileSystemWatcher doesn't watch files: it watches the file system. In this case you'll find that there will be at least the Deleted event raised when the file is removed.