Ohad's Blog

Lets talk about .net !

Mirror at:
blogs.microsoft.co.il

News

         Ohad Israeli's Facebook profile
      

C# Code Snippts

Favorite Blogs

Israeli .Net Bloggers

Drive Free Space

There are several ways to get the drive free space:

1. The interop way.

using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
public static extern bool GetDiskFreeSpaceEx(
        string lpDirectoryName,
        out UInt64 lpFreeBytesAvailable,
        out UInt64 lpTotalNumberOfBytes,
       
out UInt64 lpTotalNumberOfFreeBytes);

ulong freeBytesAvailable = 0;
ulong totalNumberOfBytes = 0;
ulong totalNumberOfFreeBytes = 0;

GetDiskFreeSpaceEx(
   "c:\\",
   out freeBytesAvailable,
   out totalNumberOfBytes,
   out totalNumberOfFreeBytes);

2. The WMI Way

We can use WMI by connecting to the “root\\cimv2” namespace and using the “Win32_LogicalDisk” class.  Programming WMI isn’t pretty, but you can use the WMI extensions for VS ‘03 Server Explorer which makes it tolerable. Once installed, you’ll get a list of the management classes in server explorer and you can simply drag and drop the disk volume that you want to pull information from onto your application designer.

You can then show free space on the volume with one line of code: MessageBox.Show(logicalDisk1.FreeSpace.ToString());

using System;
using System.Management;

tatic void Main(string[] args)
{
   
WqlObjectQuery wmiquery = new WqlObjectQuery("SELECT * FROM Win32_LogicalDisk WHERE DeviceID = 'C:'");
   
ManagementObjectSearcher wmifind = new ManagementObjectSearcher(wmiquery);

   foreach (ManagementObject mobj in wmifind.Get()) 
   
{
      Console.WriteLine("Description: " + mobj["Description"]);
      Console.WriteLine("File system: " + mobj["FileSystem"]);
      Console.WriteLine("Free disk space: " + mobj["FreeSpace"]);
      Console.WriteLine("Size: " + mobj["Size"]);
   }
}

3. The Whidbey Way

System.IO.DriveInfo.AvailableFreeSpace

Posted: Aug 08 2004, 11:43 AM by Ohad Israeli | with 3 comment(s)
Filed under:

Comments

仪表 said:

Is there any other way to get the space of disk?
# August 8, 2004 5:59 AM

Jerry Pisk said:

Just make sure you realize that C:\Directory doesn't have to be the same disk as C:\. Do not assume that everything below C:\ is on C disk.
# August 8, 2004 4:34 PM

driver free space said:

how to find drivers free space in java for windows based system

# November 20, 2006 6:58 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)