Windows Forms: How do I retrieve disk information in C#

This post shows you How to retrieve disk information in C# Windows Forms Application.

Dragging Combobox, Label 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 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();
        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.

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

Related Posts