- FileInfo and DirectoryInfo
- FileSystem class
These are non-static classes in the System.IO namespace that allow you to get almost any kind of information about files and folders and also allow operations like Deleting, Creating, Copying, Moving, etc. They are located in the System.IO namespace. Their constructors take a string that specifies the full path of the directory or file concerned.
If the file or directory does not actually exist, an exception is not thrown - just the Exists property is set to false. Once the instance is set, one can read as well as write properties like LastAccessTime, LastWriteTime, CreationTime and Attributes. The methods of DirectoryInfo class are more for the purpose of browsing through the file system while FileInfo instances are more often used to open streams to the file in question. This may be the reason why DirectoryInfo lacks the Length property of FileInfo which returns the size in bytes. One can write a tiny extension method for a DirectoryInfo instance:
Although these classes can be used to move and copy files and folders, they are less preferable than the FileSystem class which we'll discuss later in this post.
This class allows you to access any information about any drive in the machine. It is also located in the System.IO namespace. It provides a crucial single static method called GetDrives() which returns all the drives in the machine as an array of DriveInfo instances. Each of the DriveInfo instances can then be used to obtain drive information in properties like AvailableFreeSpace, TotalFreeSpace, DriveFormat, DriveType, Name, TotalSize and VolumeLabel. Perhaps the most important of these is the DriveType property which is an enum that provides for as many as 7 drive types viz. CDRom, Fixed, Removable, Network, NoRootDirectory, Ram and Unknown.
Here's a sample method to get names of all removable drives:
This class allows you to move and copy files and folders. Though this can also be achieved with the DirectoryInfo and FileInfo classes as well, the difference is that FileSystem class hands over the transfer to the OS, so the OS provides the standard progress bar UI and the application can proceed normally. With the Info classes, the application is responsible for the transfer and so does not proceed to the next instruction until the transfer is complete, resulting in undesirable UI latency especially if the file or folder involved is large.
It is located in a completely disparate Microsoft.VisualBasic.FileIO namespace.
Other than just transferring files and folders, the FileSystem class provides in fact a wide range of static methods that emulate the behavior of other classes like FileStream, FileInfo and DirectoryInfo. A quick view and you'll know what I mean.
So, I suppose I covered all the .NET classes for Directories and Files. I hope it is useful to you!