Recipe 12.24. Waiting for an Action to Occur in the FilesystemProblemYou 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. SolutionThe 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-13, which waits for an actionmore specifically, the action of creating the Backup.zip file somewhere on the C:\ driveto 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-13. WaitForZipCreation method
The code for PauseAndCreateFile is listed here. It is in the form of a WaitCallback to be used as an argument to QueueUserWorkItem on the ThreadPool class. QueueUserWorkItem will run PauseAndCreateFile on a thread from the .NET thread pool: void PauseAndCreateFile(Object stateInfo) { try { string[] data = (string[])stateInfo; // Wait a sec… Thread.Sleep(1000); // Create a file in the temp directory. string path = data[0]; string file = path + data[1]; Console.WriteLine("Creating {0} in PauseAndCreateFile…",file); using (FileStream fileStream = File.Create(file)) { // Use fileStream var… } } catch(Exception e) { Console.WriteLine(e.ToString( )); throw; } } DiscussionThe WaitForChanged method returns a WaitForChangedResult structure that contains the properties listed in Table 12-12.
The way we are currently making the WaitForChanged call could possibly block indefinitely. To prevent you from hanging forever on the WaitForChanged call, you can specify a timeout value of 3 seconds as follows: WaitForChangedResult result = fsw.WaitForChanged(WatcherChangeTypes.Created, 3000); See AlsoSee the "FileSystemWatcher Class," "NotifyFilters Enumeration," and "Wait-ForChangedResult Structure" topics in the MSDN documentation. |