In this post, we will be discussing how to find the directory drive and the size of drive in C#. This can be useful where application might want to check for drive size or remaining size of drive before getting started. Below is the snippet of implementation:
FileInfo f = new FileInfo(dirPath); //dirPath is the directory path
string drive = Path.GetPathRoot(f.FullName); //Get the drive name - if path is C:\user\desktop it will return "C:\"
To get the drive information in C#, one can use DriveInfo Class from System.IO namespace. A single DriveInfo object models one computer drive. Through that object we can access the drive’s information, like its name label,drive’s capacity, like free space amount or total size.
Below are the code snippets for getting the disk space of a drive –
DriveInfo dInfo = new DriveInfo(drive); //Create instance of DriveInfo Class
long availFreeSize = dInfo.AvailableFreeSpace; //this will get available freespace
long totalFreeSize = dInfo.TotalFreeSpace; //returns drive's total free space.
long totalSize = dInfo.TotalSize; //returns drive's total capacity.