12.12. Waiting for an Action to Occur in the Filesystem
Problem
You need to be notified when a particular event occurs in the filesystem, such as the renaming of a 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 by the WaitForZipCreation method shown in Example 12-2, 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 spin off a thread from the ThreadPool to execute the PauseAndCreateFile method, which does the actual work of creating the file. By doing this in a background thread, we allow the FileSystemWatcher to detect the file creation.
Example 12-2. WaitForZipCreation method
public void WaitForZipCreation(string path, string fileName)
{
FileSystemWatcher fsw = null; try { using (fsw = new FileSystemWatcher()) { string [] data = new string[] {path,fileName}; fsw.Path = path; fsw.Filter = fileName; fsw.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access