Search code examples
c#pinvoke

Get the cluster size of a disk in C#--Get error on 'GetDiskFreeSpace'


I am trying to get the cluster size of a disk in C#. Everything I have found says to use "GetFreeDiskSpace," but I can't get it to work. It appears as if I am missing a using or something.

When I Google the The name 'GetDiskFreeSpace' does not exist in the current context it brings up everything except for this specific error. If I do an exact phrase search, Google says nothing is found and then displays the non-exact phrase search results.

I am trying to determine where the GetFreeDiskSpace comes from, not how to fix the The name 'UnknownKeyWord' does not exist in the current context message.

I need to get the actual cluster size of a disk, not so I can determine the size on disk, but so I can populate a ComboBox.

NOTE: I am using VS 2010.

Here are the usings I have:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
using System.Management;
using System.Runtime.InteropServices;

I also have the following:

// Pinvoke for API function
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]

The code (which is not finished...I need to parse out the information from GetFreeDiskSpace) I have to get the cluster size is:

private void btnRefreshDrives_Click(object sender, EventArgs e)
{
    DriveInfo[] allDrives = DriveInfo.GetDrives();
    foreach (DriveInfo d in allDrives)
    {
        if (d.IsReady)
        {                    
            strDriveInfo = d.Name + " " + d.VolumeLabel;
            strCurrentFS = d.DriveFormat;
            strDriveLetter = d.Name;
            // The GetFreeDiskSpace has the red squiggly line under it in VS.
            ClusterSize = SectorsPerCluster * BytesPerSector;
            GetDiskFreeSpace(strDriveLetter, out SectorsPerCluster, out BytesPerSector, out NumberOfFreeClusters, out TotalNumberOfClusters);
        }
    }
}

Solution

  • If you want to use GetFreeDiskSpace, you need to import the function definition:

    [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
    static extern bool GetDiskFreeSpace(string lpRootPathName, 
       out ulong lpSectorsPerCluster, 
       out ulong lpBytesPerSector, 
       out ulong lpNumberOfFreeClusters, 
       out ulong lpTotalNumberOfClusters);