C # How to obtain the disk space,
Reference page:
Http://www.yuanjiaocheng.net/CSharp/csharp-class.html
Http://www.yuanjiaocheng.net/CSharp/csharp-variable.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-data-types.html
Http://www.yuanjiaocheng.net/CSharp/cshart-value-reference-type.html
Http://www.yuanjiaocheng.net/CSharp/Csharp-keys.html
Method 1: Use the System. IO. DriveInfo. GetDrives method to obtain
///// Obtain the total space size of the specified drive (unit: B) ///// you only need to enter the letter representing the drive (uppercase) /// public static long GetHardDiskSpace (string str_HardDiskName) {long totalSize = new long (); str_HardDiskName = str_HardDiskName + ":\\"; System. IO. driveInfo [] drives = System. IO. driveInfo. getDrives (); foreach (System. IO. driveInfo drive in drives) {if (drive. name = str_HardDiskName) {totalSize = drive. totalSize/(1024*1024*1024);} return totalSize;} // obtain the total size of the remaining space on the specified drive (unit: B) ///// enter the letter representing the drive. // public static long GetHardDiskFreeSpace (string str_HardDiskName) {long freeSpace = new long (); str_HardDiskName = str_HardDiskName + ": \ "; System. IO. driveInfo [] drives = System. IO. driveInfo. getDrives (); foreach (System. IO. driveInfo drive in drives) {if (drive. name = str_HardDiskName) {freeSpace = drive. totalFreeSpace/(1024*1024*1024);} return freeSpace ;}
Method 2: Use ManagementClass ("Win32_LogicalDisk") to obtain
List <Dictionary <string, string> diskInfoDic = new List <Dictionary <string, string> (); ManagementClass diskClass = new ManagementClass ("Win32_LogicalDisk"); ManagementObjectCollection disks = diskClass. getInstances (); foreach (ManagementObject disk in disks) {Dictionary <string, string> diskInfo = new Dictionary <string, string> (); try {// disk Name diskInfo ["Name"] = disk ["Name"]. toString (); // disk Description diskInfo ["Description"] = disk ["Description"]. toString (); // total disk capacity, available space, used space if (System. convert. toInt64 (disk ["Size"])> 0) {long totalSpace = System. convert. toInt64 (disk ["Size"])/MB; long freeSpace = System. convert. toInt64 (disk ["FreeSpace"])/MB; long usedSpace = totalSpace-freeSpace; diskInfo ["totalSpace"] = totalSpace. toString (); diskInfo ["usedSpace"] = usedSpace. toString (); diskInfo ["freeSpace"] = freeSpace. toString ();} diskInfoDic. add (diskInfo);} catch (Exception ex) {Throw ex ;}}
For more IT related information and technical articles, welcome to my personal website: http://www.zuowenjun.cn/