C# .NET - get free space - Asked By mostafa hamdy on 11-Oct-10 05:01 AM

hello all
I have C# application , and I want to create some method with it to pass the hard drive name like(C,D or G...etc)  and the method return thr free space on this drive , please if any body get what I mean and can help me or tell me about some url may help me in doing that please send me
regards
Mostafa
DL M replied to mostafa hamdy on 11-Oct-10 05:37 AM
you can use Use WMI to retrieve the freespace of a selected HDD

Code Sample
//Namespace reference
using System.Management

/// <summary>
/// method to retrieve the HDD's freespace
/// </summary>
/// <param name="drive">Drive letter to get free space from (optional)</param>
/// <returns>The free space of the selected HDD</returns>
public double GetHDDFreeSpace(string drive)
{
    //check to see if the user provided a drive letter
    //if not default it to "C"
    if (drive == "" || drive == null)
    {
      drive = "C";
    }
    //create our ManagementObject, passing it the drive letter to the
    //DevideID using WQL
    ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\"" + drive + ":\"");
    //bind our management object
    disk.Get();
    //return the free space amount
    return Convert.ToDouble(disk["FreeSpace"]);
}

you will get more info from below links
http://stackoverflow.com/questions/2065045/wipe-free-space-on-hard-disk-drive-using-c
http://efreedom.com/Question/1-3210010/Calculate-Free-Disk-Space


Venkat K replied to mostafa hamdy on 11-Oct-10 05:46 AM
Hi mostafa,

Write the following function in button click where you need to calculate the free size of drive:

//Import namespace
using System.Runtime.InteropServices;
//Declare the Win32 API using the attribute "DllImport" so that it can be called from managed code.
[DllImport("kernel32", CharSet=CharSet.Auto)] static extern int GetDiskFreeSpaceEx(  string lpDirectoryName,  out ulong lpFreeBytesAvailable,  out ulong lpTotalNumberOfBytes,  out ulong lpTotalNumberOfFreeBytes);

//Call the API from managed code (C# or VB.NET) to retrieve information about the specific disk drive.

ulong freeBytesAvailable, totalBytes, freeBytes;
// Call the Win32 API to retrieve disk space information.
GetDiskFreeSpaceEx ( "C:", out freeBytesAvailable, out totalBytes, out freeBytes );
System.Diagnostics.Debug.WriteLine( "Total space : " + totalBytes + " Bytes" );
System.Diagnostics.Debug.WriteLine( "Free space : " + freeBytes + " Bytes" );
System.Diagnostics.Debug.WriteLine( "Available Free space : " + freeBytesAvailable + " Bytes" );



Thanks
Anurag replied to mostafa hamdy on 11-Oct-10 07:15 AM
I have used this in my application and hope it will help u too:

I dont know how gud it is but have created it on my own and can search upto 5 partitions in a computer system
Just call this method in post back or wherever u want to.

public string fn_GetHddDetails()
      {
        int int_Flag = 0;
        double dbl_FreeSpace;
        double dbl_HddSize;
        String str_HddUtilization = string.Empty;
        try
        {
          //ManagementScope scope = new ManagementScope("\\\\127.0.0.1\\root\\cimv2");
          //scope.Connect();
          ObjectQuery query = new ObjectQuery("SELECT FreeSpace,Name, Size FROM Win32_LogicalDisk where DriveType = 3");
          ManagementObjectSearcher searcherdisk = new ManagementObjectSearcher(query);
          ManagementObjectCollection queryCollection = searcherdisk.Get();

          foreach (ManagementObject queryObjdisk in queryCollection)
          {
            if (queryObjdisk["FreeSpace"] != null)
            {
              int_Flag++;
              if (int_Flag == 1)
              {
                string name = Convert.ToString(queryObjdisk["Name"]);
                dbl_FreeSpace = Convert.ToDouble(queryObjdisk["FreeSpace"]);
                dbl_HddSize = Convert.ToDouble(queryObjdisk["Size"]);
                str_HddUtilization = name + Convert.ToString(System.Math.Round(((dbl_HddSize - dbl_FreeSpace) / dbl_HddSize) * 100,2)) + "%";
              }
              else if (int_Flag == 2)
              {
                string name = Convert.ToString(queryObjdisk["Name"]);
                dbl_FreeSpace = Convert.ToDouble(queryObjdisk["FreeSpace"]);
                dbl_HddSize = Convert.ToDouble(queryObjdisk["Size"]);
                str_HddUtilization += ", " + name + Convert.ToString(System.Math.Round(((dbl_HddSize - dbl_FreeSpace) / dbl_HddSize) * 100, 2)) + "%";
              }
              else if (int_Flag == 3)
              {
                string name = Convert.ToString(queryObjdisk["Name"]);
                dbl_FreeSpace = Convert.ToDouble(queryObjdisk["FreeSpace"]);
                dbl_HddSize = Convert.ToDouble(queryObjdisk["Size"]);
                str_HddUtilization += ", " + name + Convert.ToString(System.Math.Round(((dbl_HddSize - dbl_FreeSpace) / dbl_HddSize) * 100, 2)) + "%";
              }
              else if (int_Flag == 4)
              {
                string name = Convert.ToString(queryObjdisk["Name"]);
                dbl_FreeSpace = Convert.ToDouble(queryObjdisk["FreeSpace"]);
                dbl_HddSize = Convert.ToDouble(queryObjdisk["Size"]);
                str_HddUtilization += ", " + name + Convert.ToString(System.Math.Round(((dbl_HddSize - dbl_FreeSpace) / dbl_HddSize) * 100, 2)) + "%";
              }
              else if (int_Flag == 5)
              {
                string name = Convert.ToString(queryObjdisk["Name"]);
                dbl_FreeSpace = Convert.ToDouble(queryObjdisk["FreeSpace"]);
                dbl_HddSize = Convert.ToDouble(queryObjdisk["Size"]);
                str_HddUtilization += ", " + name + Convert.ToString(System.Math.Round(((dbl_HddSize - dbl_FreeSpace) / dbl_HddSize) * 100, 2)) + "%";
              }
            }

            else if (queryObjdisk["FreeSpace"] == null && int_Flag == 0)
            {
             // "Server cannot be accessed";
            }
          }
          return str_HddUtilization;
        }
        catch
        {
          //ex.Message.ToString();
          return null;
        }
        finally
        {

        }
      }

If u have to access other system's details then u must have a admin right account on that system and pass it on with options object like this:
ConnectionOptions options = new ConnectionOptions();
        options.Username = username;
        options.Password = password;
        options.Authority = "ntlmdomain:UrDomain.com";