首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 取得電腦磁碟空間:DriveInfo.GetDrives 與 TotalSize 完整範例

     編輯:關於C語言

核心 API

  • System.IO.DriveInfo.GetDrives():取得所有邏輯磁碟機資訊陣列。
  • DriveInfo.TotalSize:磁碟總容量 (位元組)。

完整 WinForms 範例

private void Form1_Load(object sender, EventArgs e)
{
    DriveInfo[] drives = DriveInfo.GetDrives();
    foreach (DriveInfo d in drives)
        comboBox1.Items.Add(d.Name);
}

private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
    DriveInfo[] drives = DriveInfo.GetDrives();
    foreach (DriveInfo d in drives)
    {
        if (comboBox1.SelectedItem.ToString() == d.Name)
        {
            // 顯示 KB (TotalSize / 1024)
            textBox1.Text = (d.TotalSize / 1024).ToString();
            break;
        }
    }
}

補充說明

  • DriveInfo 還提供 AvailableFreeSpace、TotalFreeSpace、DriveFormat、DriveType 等屬性。
  • 若需顯示 MB/GB,自行換算 (/1024/1024 或 /1024/1024/1024)。
  • 需參考 System.IO 命名空間。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved