5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#でドライブ毎のディスク容量と空き容量取得

Posted at

Windowsサーバのパフォーマンスチェックアプリを作成する際に、HDD空き容量も取得する処理を実装するときに調べた自分メモです。
コンソールアプリケーションにコピペ->開始で動作します。コード詳細はコメントを参照願います。

using System;
using System.IO;
using System.Collections;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // トライブすべてを取得
            string[] drives = Directory.GetLogicalDrives();
            // foreachで取得したドライブ配列にループ
            foreach (string s in drives)
            {
                Hashtable data = new Hashtable();
                DriveInfo drive = new DriveInfo(s);
                //ドライブの準備ができているか調べる
                if (drive.IsReady)
                {
                    //TotalSizeを取得して変換してHashに格納。
                    data.Add("TotalSize(" + s + "):", ToGigaByte(Convert.ToDouble(drive.TotalSize)));
                    //TotalFreeSpaceを取得して変換してHashに格納。
                    data.Add("TotalFree(" + s + "):", ToGigaByte(Convert.ToDouble(drive.TotalFreeSpace)));
                }
                foreach (DictionaryEntry h in data)
                {
                    Console.WriteLine(h.Key + " " + h.Value);
                }
            }
            Console.ReadLine();
        }
        // GB換算して戻すメソッド(見やすさ優先)
        static int ToGigaByte(Double calcTarget)
        {
            Double i = calcTarget / 1024; //Kbyte
            i /= 1024; //MB
            i /= 1024; //GB
            i = Math.Ceiling(i);
            return Convert.ToInt16(i);
        }
    }
}
5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?