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 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.
- See NotifyFilters for possible watches.
- 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.
- 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
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



