WMI the unsung hero (or How to listen for directory changes in windows)

There is a feature in Windows that I don't think everyone is aware of, its called the Windows Management Interface (or WMI) its useful for a bunch of things that I wont go into here but my friend Brian is working on a new version of his Media Center ad-in called My Movies.

This new version will will be re-architected to have a system service that integrates with DVD changers as well as implements a folder monitoring concept.

There are basically two models available for building a folder monitoring feature in a component like this:

  1. Register with Windows for notifications when a monitored folder gets changed.
  2. Enumerate all folders, compare the results with your already indexed content and act upon the delta

Generally speaking a component usually needs to implement both concepts, on the surface #1 sounds the best after all you don't have to periodically on scan the system which can be cpu intensive and time consuming for large collections.

But what about when your not running, you need to be able to notice changes that occurred during these cases too.

Well this is where #1 and WMI come into play, WMI can be used to say "let me know when something has changed in this location", the bellow example shows how this can be done in C# (borrowed from here)

StringBuilder wqlText = new StringBuilder();

wqlText.Append("SELECT * FROM __InstanceOperationEvent WITHIN 1 WHERE
TargetInstance ISA ");
wqlText.AppendFormat("{0} ", "'CIM_DirectoryContainsFile'");
wqlText.AppendFormat(" AND TargetInstance.GroupComponent ={0}",
"'Win32_Directory.Name=\"C:\\\\\\\\Data\"'");


WqlEventQuery query = new WqlEventQuery(wqlText.ToString());

There are other ways to accomplish the same thing in .NET, one might even argue simpler ways (but I couldn't have talked about WMI then could I?), specifically I am referring to the FileSystemWatcher class.

Print | posted on Monday, March 12, 2007 8:26 PM

Feedback

No comments posted yet.
Title  
Name  
Email
Url
Comments   
Please add 2 and 7 and type the answer here: