How to get free and available and total disk space in KB using kernel32.dll in C#

1 Answer

0 votes
using System.Runtime.InteropServices;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
                                    out ulong lpFreeBytesAvailable,
                                    out ulong lpTotalNumberOfBytes,
                                    out ulong lpTotalNumberOfFreeBytes);
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ulong freeBytesAvailable;
            ulong totalNumOfBytes;
            ulong totalNumOfFreeBytes;

            if (!GetDiskFreeSpaceEx("C:\\", out freeBytesAvailable, out totalNumOfBytes, out totalNumOfFreeBytes))
            {
                Console.Error.WriteLine("GetDiskFreeSpaceEx Error");
            }
            else
            {
                label1.Text = "";
                label1.Text += "Available: " + string.Format("{0:n}", freeBytesAvailable / 1024) + " k" + Environment.NewLine;
                label1.Text += "Total: " + string.Format("{0:n}", totalNumOfBytes / 1024) + " k" + Environment.NewLine;
                label1.Text += "Total free: " + string.Format("{0:n}", totalNumOfFreeBytes / 1024) + " k" + Environment.NewLine;
            }
        }
    }
}



/*
 * run:
 *
 * Available: 528,781,604.00 k
 * Total: 976,132,092.00 k
 * Total free: 528,781,604.00 k
 * 
 */

 



answered Aug 19, 2023 by avibootz

Related questions

1 answer 145 views
145 views asked Aug 20, 2023 by avibootz
1 answer 110 views
110 views asked Aug 20, 2023 by avibootz
1 answer 111 views
111 views asked Aug 20, 2023 by avibootz
1 answer 102 views
1 answer 141 views
...