Access Files and Folders by Using the File System Classes

The .NET Framework provides a set of classes to work with the file system, thus creating, modifying and opening files, directories, monitoring changes, etc. These classes live in the System.IO namespace. Here’s a brief list of them, and what they are capable of:

Classes of System.IO
DriveInfo Class Provides information about installed drives on the system.
Directory Class Static class with static methods to work with the directory system.
DirectoryInfo Class A class to work with the directory system through instances of it.
File Class Static class with static methods to work with the file system.
FileInfo Class A class to work with the file system thorough instances of it.
FileSystemInfo Class The base class of DirectoryInfo and FileInfo. Use it when you work with both, or extend it.
FileSystemWatcher Class Look for changes in a given location, and forwards them to your code.

 

Let’s proceed from the biggest to the smallest, so DriveInfo comes first. DriveInfo has a static method, GetDrives which returns an array of the available drives (as DriveInfo instances) on your system. To get a list of them, use the following code:

foreach(DriveInfo di in DriveInfo.GetDrives())
{
                Console.WriteLine(di.Name);
}

When you’d like to further examine each drive, you can create an instance of DriveInfo. The sole constructor accepts a drive name in string format. When you’ve created it, you can query the following properties for information:

DriveInfo Properties
AvaliableFreeSpace The available free space.
DriveFormat NTFS/FAT32
DriveType Enumeration: CDRom, Fixed, Network, NoRootDirectory, Ram, Removable, Unknown
IsReady Is it ready?
Name I can’t explain it any further.
RootDirectory The root directory.
TotalFreeSpace The total amount of free space on the drive.
TotalSize The total size of the drive.
VolumeLable Guess.

 

Directory and DirectoryInfo

These classes are for the same purposes. As I mentioned at the beginning, Directory is a static class with static methods. Use the methods of it when you need to perform one task with a directory. For performance reasons, you should use the DirectoryInfo class when there’s multiple things to do with one directory. Another table:

Task Directory DirectoryInfo
Create a directory Create method, accepts string path, returns DirectoryInfo. Create method, creates a directory from the instance. Returns void.
Delete a directory Delete method, accepts path as string, and whether or not to delete subdirectories, files as bool. Delete method, deletes the current instance. Accepts a bool if you’d like to delete subdirectories and files.
Move a directory Move method, accepts a from and to string, returns void. MoveTo method, accepts a to string.
Get the subdirectories GetDirectories, accepts a where string, returns an array of strings. Can be filtered. GetDirectories method, returns an array of strongly typed DirectoryInfos. Can be filtered.
Get files GetFiles, accepts a where string and filters. Returns an array of strings. GetFiles, returns a strongly typed array of FileInfos. Can be filtered.

 

You can get or set properties of directories through the static methods of the Directory class. You can read or write these properties in the instances of DirectoryInfo also.

File and FileInfo

The logic behind File and FileInfo is the same as it is with Directory and DirectoryInfo. If you need to do one or two tasks with a file, use the static File class, else use an instance of FileInfo.

Task File FileInfo
Create a file Create: creates or overwrites a file at the specified path. Returns FileStream.

CreateText: creates or opens a file at the specified path. Returns StreamWriter.

The same as File.
Delete a file Delete. Throws an exception if the file specified don’t exists. Same.
Copy a file Copy method. String from, string to, bool overwritre. CopyTo method. String to,  bool overwrite.
Move (cut) a file Move method. String from, string to. MoveTo method, string to.
Open a file Open: returns StreamReader, opens a file with the specified FileMode and FileAccess.

OpenRead: returns FileStream, opens a file for reading.

OpenText: returns StreamReader, opens a UTF-8 encoded file for reading.

OpenWrite: returns FileStream, opens a file for writing.

Same.

 

FileSystemWatcher

FileSystemWatcher is a class that monitors the file system, and raises events when something specified happens. To start listening, you should specify a filter (Filter attribute, use empty string, wildcards or specify a file name to monitor), set the Path variable to the path you’re interested, narrow the type of events by setting the NotifyFilter property to one of the NotifyFilters (Attributes, CreationTime, DirectoryName, FileName, LastAccess, LastWrite, Security, Size), rig the appropriate event handlers, and set the EnableRaiseEvents property to true. There are five events, namely:

  • Created: occurs when a file or directory at the specified path is created. Uses FileSystemEventArgs. Exposes Name, FullPath and ChangeType properties.
  • Changed: occurs when a file or directory at the specified path is changed. Uses FileSystemEventArgs.
  • Deleted: occurs at deletion. Uses FileSystemEventArgs.
  • Error: occurs when the internal buffer overflows. Uses ErrorEventArgs. Use the GetException method of ErrorEventArgs to get the exception.
  • Renamed: occurs when a file or directory is renamed. Uses RenamedEventArgs, exposes FullPath, Name, OldFullPath and OldName properties.

 

Further Readings

FileSystemInfo Class

Directory Class

DirectoryInfo Class

File Class

FileInfo Class

FileSystemWatcher Class

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: