File System Monitoring

Chapter 9

File System Monitoring

I've come across applications that are designed to wait for files to show up in a particular directory and then process them—for example, an application that imports data from a file into a database. Data files can be downloaded from a mainframe or transferred to an input directory by some other means, and then an application imports them into a database. Instead of constantly polling the directory for new files, the application can wait for notifications indicating that a new file has been created. You can create programs with this capability in Visual Basic 6, but you have to use and understand Win32 APIs. This task becomes trivial in Visual Basic .NET by using the .NET Framework classes. The implementation of such a program in Microsoft .NET is also consistent with the way you do everything else in .NET, so the learning curve is minimal.

The .NET Framework has a built-in class named System.IO.FileSystemWatcher that a program can use to watch the file system. This class provides properties that let you set which path to monitor and specify whether you are interested in changes at the file or subdirectory level. The System.IO.FileSystemWatcher class also lets you specify which filenames and types to watch for. (For example, *.txt is the instruction you use to watch for changes to all text files.) Finally, you can even specify the types of changes you're interested in monitoring—for instance, new file creations, changes to file attributes, or changes to file size.

After you establish what to watch and what to watch for, you can wire in event handlers for the various events that interest you. The FileSystemWatcher class events that we can trap are Changed, Created, Deleted, Error, and Renamed. To handle an event, you write an event handler with the same declaration as the FileSystemEventHandler delegate and then add this handler to the FileSystemWatcher class. (The program we build in this chapter will illustrate the use of delegates.) This delegate-based architecture lets you add multiple handlers for the same event or use one handler for multiple events, which you couldn't do in Visual Basic 6.



Coding Techniques for Microsoft Visual Basic. NET
Coding Techniques for Microsoft Visual Basic .NET
ISBN: 0735612544
EAN: 2147483647
Year: 2002
Pages: 123
Authors: John Connell

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net