FileSystemInfo Class and FileSystemWatcher Class

Overview

  • FileSystemInfo
    • FileSystemInfo forms the base for FileInfo and DirectoryInfo, but not DriveInfo.
    • Information contained by FileSystemInfo is cached on first call, use Refresh() to update it.
    • Absolute, Relative and UNC paths are allowed as format.
    • Get information from Attributes using bitwise operators.
  • FileSystemWatcher
    • Can be used to monitor a directory for creation, deletion, renaming and modification of files.
    • Possible to use Filters for both the mask to watch and the type of notifications.
    • The internal buffer can overflow if too many notifications are happening at once.
      • This will trigger the Error event, so you can deal with it.

Examples

Checking FileType

FileSystemInfo a = new FileInfo(@"\\davidcxp\Public\Hello.txt");
FileSystemInfo b = new DirectoryInfo(@"C:\Public");
 
Console.WriteLine("{0}: {1}, created at {2}", 
                    ((a.Attributes & FileAttributes.Directory) != 0) ? "Directory" : "File",
                    a.FullName,
                    a.CreationTime);
 
Console.WriteLine("{0}: {1}, created at {2}",
                    ((b.Attributes & FileAttributes.Directory) != 0) ? "Directory" : "File",
                    b.FullName,
                    b.CreationTime);

Watching Directory

static void Main(string[] args)
{
    FileSystemWatcher a = new FileSystemWatcher();
    a.Path = @"C:\Public\";
    a.Filter = "*.txt";
    a.NotifyFilter = NotifyFilters.FileName;
    a.Created += new FileSystemEventHandler(Change);
    a.Deleted += new FileSystemEventHandler(Change);
    a.Changed += new FileSystemEventHandler(Change);
    a.Renamed += new RenamedEventHandler(Renamed);
    a.EnableRaisingEvents = true;
 
    Console.ReadLine();
    // Created C:\Public\New Text Document.txt
    // Renamed C:\Public\New Text Document.txt C:\Public\Watch.txt
    // Deleted C:\Public\Watch.txt
}
 
static void Change(object sender, FileSystemEventArgs e)
{
    Console.WriteLine(e.ChangeType + " " + e.FullPath);
}
 
static void Renamed(object sender, RenamedEventArgs e)
{
    Console.WriteLine(e.ChangeType + " " + e.OldFullPath + " " + e.FullPath);
}