O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.24. Waiting for an Action to Occurin the Filesystem

Problem

You need to be notified when a particular event occurs in the filesystem, such as the renaming of a particular file or directory, the increasing or decreasing of the size of a file, the user deleting a file or directory, the creation of a file or directory, or even the changing of a file or directory’s attribute(s). However, this notification must occur synchronously. In other words, the application cannot continue unless a specific action occurs to a file or directory.

Solution

The WaitForChanged method of the FileSystemWatcher class can be called to wait synchronously for an event notification. This is illustrated in the following method, which waits for an action—more specifically, the action of creating the Backup.zip file somewhere on the C:\ drive—to be performed before proceeding on to the next line of code, which is the WriteLine statement. Finally, we ask the ThreadPool to use a thread to go create the file in question using the PauseAndCreateFile method, so that the FileSystemWatcher can detect the file creation:

public void WaitForZipCreation(string path, string fileName) { FileSystemWatcher fsw = null; try { fsw = new FileSystemWatcher( ); string [] data = new string[] {path,fileName}; fsw.Path = path; fsw.Filter = fileName; fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Run the code to generate the file we are looking for ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required