Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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 ...
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.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata