[C#]查詢硬碟剩餘空間(透過WinAPI)

  • 24676
  • 0
  • 2010-08-02

查詢硬碟剩餘的空間

這是在藍色小舖上遇到的問題,如何查詢硬碟剩餘空間,我們可以透過Windows API 函數 GetDiskFreeSpaceEx 來達成,MSDN的相關說明:
http://msdn.microsoft.com/en-us/library/aa364937(VS.85).aspx

此外,GetDiskFreeSpace與GetDiskFreeSpaceEx,不一樣的地方是,GetDislFreeSpaceEx傳遞值是 8 Bytes,因此可以得到2GB以上的數據。

而以下程式可以根據需求,改成查詢硬碟總容量或者已使用容量

程式碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;    


namespace WindowsApplication5
{
    public partial class Form1 : Form
    {        
        public Form1()
        {
            InitializeComponent();
        }

            
        private void button1_Click(object sender, EventArgs e)
        {
            string drive = "D:\\";      // 要查詢剩餘空間的磁碟
            ulong FreeBytesAvailable;
            ulong TotalNumberOfBytes;
            ulong TotalNumberOfFreeBytes;
            bool success = GetDiskFreeSpaceEx(drive, out FreeBytesAvailable, out TotalNumberOfBytes, out TotalNumberOfFreeBytes);

            if (!success)
                throw new System.ComponentModel.Win32Exception();

            double free_kilobytes = (double)(Int64)TotalNumberOfFreeBytes / 1024.0;
            double free_megabytes = free_kilobytes / 1024.0;
            double free_gigabytes = free_megabytes / 1024.0;
            MessageBox.Show(drive + " 剩餘 " + free_gigabytes.ToString() + " GB");      
        }


        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
        out ulong lpFreeBytesAvailable,
        out ulong lpTotalNumberOfBytes,
        out ulong lpTotalNumberOfFreeBytes);
    }

}

執行結果


參考
http://www.blueshop.com.tw/board/show.asp?subcde=BRD2009022411392488B&fumcde=FUM20050124191259IGD

 此外,也可以透過 System.IO來取得TotalSize與AvailableFreeSpace,可以參考
http://www.dotblogs.com.tw/fatty0860/archive/2009/02/06/7067.aspx