C#如何获取磁盘容量和已用大小

解决方案 »

  1.   

    DriveInfo.TotalFreeSpace 属性  命名空间:System.IO               DriveInfo[]   allDrives   =   DriveInfo.GetDrives();                 foreach   (DriveInfo   d   in   allDrives) 
                    { 
                            Console.WriteLine( "Drive   {0} ",   d.Name); 
                            Console.WriteLine( "     File   type:   {0} ",   d.DriveType); 
                            if   (d.IsReady   ==   true) 
                            { 
                                    Console.WriteLine( "     Volume   label:   {0} ",   d.VolumeLabel); 
                                    Console.WriteLine( "     File   system:   {0} ",   d.DriveFormat); 
                                    Console.WriteLine( 
                                            "     Available   space   to   current   user:{0,   15}   bytes ",   
                                            d.AvailableFreeSpace);                                 Console.WriteLine( 
                                            "     Total   available   space:                     {0,   15}   bytes ", 
                                            d.TotalFreeSpace);                                 Console.WriteLine( 
                                            "     Total   size   of   drive:                         {0,   15}   bytes   ", 
                                            d.TotalSize); 
                            } 
                    } 
      

  2.   

    ManagementClass mClass = new ManagementClass("Win32_LogicalDisk");
      ManagementObjectCollection moCollection = mClass.GetInstances();
      foreach (ManagementObject mObject in moCollection)
      {
      if (Int32.Parse(mObject["DriveType"].ToString()) == (int)System.IO.DriveType.Fixed)
      {
      long lDiskSize = long.Parse(mObject["Size"].ToString());
      long lfreeDiskSiz= long.Parse(mObject["FreeSpace"].ToString());   
       
      } }
    [DllImport("kernel32.dll", EntryPoint="GetDiskFreeSpaceExA")]   
      public static extern int GetDiskFreeSpaceEx (string lpRootPathName,out long lpFreeBytesAvailable,out long lpTotalNumberOfBytes,out long lpTotalNumberOfFreeBytes);   
    using System.Management;   
      using System;   
        
      ManagementPath path = new ManagementPath();   
      path.Server = "localhost";   
      path.NamespacePath = @"root\CIMV2";   
      path.RelativePath = "Win32_LogicalDisk='c:'";   
      System.Management.ManagementObject o = new ManagementObject(path);   
      Console.WriteLine("free space {0}", o["FreeSpace"]);