
FileSystemInfo Class and FileSystemWatcher Class
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
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.
- Get information from Attributes using bitwise operators.
FileSystemWatcher
- Can be used to monitor a directory for creation, deletion, renaming and modification of files.
- See NotifyFilters for possible watches.
- Filters can be set for both the file mask to watch (Filter) and the type of notifications (NotifyFilter).
- The internal buffer can overflow if too many notifications happen at once.
- This will trigger the Error event, so you can deal with it.
- Can be used to monitor a directory for creation, deletion, renaming and modification of files.
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);
}
You May Also Like

Exam 70-536 Study Notes
My study notes for Microsoft exam 70-536: .NET types, collections, generics, I/O, serialization and more, with C# examples.

Starting Exam 70-536 Study
After a burnout, I'm putting my own project on hold to study for Microsoft exam 70-536.

Design Patterns - Proxy Pattern
The Proxy Pattern, and the last article in the design patterns series, now that I've finished reading Head First Design Patterns.



