Roy Osherove

View Original

Watching your computer breath using FileSystemWatcher

Breath is the only word that came to mind to describe the regular second to second operations your computer does just to keep itself in the current state while preparing for the next states (in terms of temporary files, background processes and more).

Here's a nice exercise you can do:

  • Create a new console application
  • Paste in this code for the Main() method:
static void Main(string[] args)
        {
            FileSystemWatcher watcher = new FileSystemWatcher("c:\\");
            watcher.IncludeSubdirectories = true;
            watcher.Changed+=delegate(object sender, FileSystemEventArgs e)
                                 {
                                     string file = Path.GetFileName(e.FullPath);
                                     string dir = Path.GetDirectoryName(e.FullPath);
                                     Console.WriteLine("{0} was {1} in {2}",file,e.ChangeType,dir);
                                 };
            watcher.EnableRaisingEvents = true;
            Console.Read();
        }

Press Ctrl+F5 and just watch the screen.

Yeah, you have fancier tools(this or this) to do this job better, but it's nice to have this kind of ability built into the framework, and it's an eye opener just how much stuff goes on when you don't do anything on your computer.

If you're interested in some tips on better usage with the FileSystemWatcher, take a look here.