How do I retrieve disk information in C#

By FoxLearn 7/13/2024 4:16:24 AM   4.01K
To retrieve disk information in a C# Windows Forms Application, you can utilize the DriveInfo class from the System.IO namespace.

This class provides methods and properties to obtain information about drives on a computer, such as drive type, available space, total size, and more,

Here's a basic example of how you can get disk information:

Drag and drop the Combobox, Label controls from the Visual Studio toolbox into your form designer, then design a simple UI allows you to select a driver, then display disk information as shown below.

c# get disk information

C# get list of drives

Adding a Form_Load event handler to your form allows you to get list of drivers.

//c# get physical drives
private void frmGetDiskInfo_Load(object sender, EventArgs e)
{
    // c# get all available drives
    cboDisk.Items.AddRange(DriveInfo.GetDrives());
}

C# get disk usage

Adding a SelectedIndexChanged event handler to the Combobox allows you to get disk information.

//c# get diskspace
private void cboDisk_SelectedIndexChanged(object sender, EventArgs e)
{
    DriveInfo driveInfo = new DriveInfo(cboDisk.Text.Substring(0, 1));
    lblType.Text = driveInfo.DriveType.ToString();
    if (driveInfo.IsReady)
    {
        lblFormat.Text = driveInfo.DriveFormat;
        lblAvailableFreeSpace.Text = driveInfo.AvailableFreeSpace.ToPrettySize();
        lblTotalFreeSize.Text = driveInfo.TotalFreeSpace.ToPrettySize();
        lblTotalSize.Text = driveInfo.TotalSize.ToPrettySize();
    }
    else
    {
        lblFormat.Text = string.Empty;
        lblAvailableFreeSpace.Text = string.Empty;
        lblTotalFreeSize.Text = string.Empty;
        lblTotalSize.Text = string.Empty;
    }
}

Creating a converter extension method allows you to convert size to prettysize.

// Helper method to format bytes into appropriate unit
public static class ConverterExtension
{
    private const long Kb = 1024;
    private const long Mb = Kb * 1024;
    private const long Gb = Mb * 1024;
    private const long Tb = Gb * 1024;

    public static string ToPrettySize(this long value, int decimalPlaces = 0)
    {
        var tb = Math.Round((double)value / Tb, decimalPlaces);
        var gb = Math.Round((double)value / Gb, decimalPlaces);
        var mb = Math.Round((double)value / Mb, decimalPlaces);
        var kb = Math.Round((double)value / Kb, decimalPlaces);
        string size = tb > 1 ? string.Format("{0}Tb", tb)
            : gb > 1 ? string.Format("{0} Gb", gb)
            : mb > 1 ? string.Format("{0} Mb", mb)
            : kb > 1 ? string.Format("{0} Kb", kb)
            : string.Format("{0} byte", Math.Round((double)value, decimalPlaces));
        return size;
    }
}

This c# example returns disk information including: Total free size, Available free space, Format, Type...etc