C# Tips


ドライブの容量を取得する


ドライブの容量を取得するにはManagementObjectクラスを使用します。
以下のコードはドライブのサイズ、使用済みサイズ、未使用サイズをDriveInfoというクラスに格納して返します。
using System.Management; //参照にDLLの追加が必要です。

class DriveInfo
{
	public UInt64 Size;
	public UInt64 Used;
	public UInt64 Available;
}

public DriveInfo getDiskSize(String drive)
{
	DriveInfo driveInfo = new DriveInfo();

	if(!Directory.Exists(drive+@":\"))
	{
		throw new DirectoryNotFoundException("The drive does not exist");
		ManagementObject disk = new ManagementObject("Win32_LogicalDisk.DeviceID=\""+drive+":\"");
		UInt64 freespace = (UInt64)disk.Properties["FreeSpace"].Value ;
		UInt64 size = (UInt64)disk.Properties["Size"].Value ;

		driveInfo.size = size;
		driveInfo.used = ((size - freespace));
		driveInfo.available = freespace;
	}

	return driveInfo;
}



目次に戻る
Copyright(c) 2008 WoodenSoldier Software