SoFunction
Updated on 2025-03-07

C# to achieve the disk space size

This article describes the method of C# to obtain disk space size. Share it for your reference. The specific implementation method is as follows:

Method 1: Use methods to obtain

Copy the codeThe code is as follows:
///  
/// Get the total space size of the specified drive (unit is B)
///  
///  Just enter the letter representing the drive (caps)
///   
public static long GetHardDiskSpace(string str_HardDiskName)
{
    long totalSize= new long();
    str_HardDiskName=str_HardDiskName +":\\";
    [] drives = ();
    foreach ( drive in drives)
    {
 if ( == str_HardDiskName)
 {
     totalSize = / (1024 * 1024 * 1024);
 }
    }
    return totalSize;
}

///  
/// Get the total remaining space size of the specified drive (unit is B)
///  
///  Just enter the letters representing the drive
///   
public static long GetHardDiskFreeSpace(string str_HardDiskName)
{
    long freeSpace = new long();
    str_HardDiskName = str_HardDiskName + ":\\";
    [] drives = ();
    foreach ( drive in drives)
    {
 if ( == str_HardDiskName)
 {
     freeSpace = / (1024 * 1024 * 1024);
 }
    }
    return freeSpace;
}


Method 2: Use ManagementClass("Win32_LogicalDisk") to obtain
Copy the codeThe code is as follows:
List<Dictionary<string, string>> diskInfoDic = new List<Dictionary<string, string>>();
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection disks = ();
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 (.ToInt64(disk["Size"]) > 0)
     {
  long totalSpace = .ToInt64(disk["Size"]) / MB;
  long freeSpace = .ToInt64(disk["FreeSpace"]) / MB;
  long usedSpace = totalSpace - freeSpace;
       diskInfo["totalSpace"]=();
  diskInfo["usedSpace"]=();
  diskInfo["freeSpace"]=();
     }
     (diskInfo);
 }
 catch(Exception ex)
 {
     Throw ex;
 }
}

I hope this article will be helpful to everyone's C# programming.