- C#方法
string driveName = "C:\\";
System.IO.DriveInfo[] drivers = System.IO.DriveInfo.GetDrives();
foreach (var drive in drivers)
{
if (driveName == drive.Name)
Console.WriteLine(drive.TotalFreeSpace / (1024 * 1024 * 1024 * 1.0f) + "G");
}
C#只能一次性获取所有的磁盘,所以如果指定某个磁盘的话则需要进行判断,并且获取到的空间单位为字节(Byte)
- C++方法
DWORD64 qwFreeBytes, qwFreeBytesToCaller, qwTotalBytes;
bResult = GetDiskFreeSpaceEx(TEXT("C:"),
(PULARGE_INTEGER)&qwFreeBytesToCaller,
(PULARGE_INTEGER)&qwTotalBytes,
(PULARGE_INTEGER)&qwFreeBytes);
if (bResult)
{
cout << "Use GetDiskFreeSpaceEx" << endl;
cout << "Total Byte: " << qwTotalBytes << endl;
cout << "FreeByte: " << qwFreeBytes << endl;
cout << "FreeByte available: " << qwFreeBytesToCaller << endl;
cout << "Free G is " << qwFreeBytesToCaller / 1024 / 1024 / 1024 * 1.0f << endl;
}
GetDiskFreeSpaceEx 函数在MSDN上解释
BOOL WINAPI GetDiskFreeSpaceEx(
_In_opt_ LPCTSTR lpDirectoryName,
_Out_opt_ PULARGE_INTEGER lpFreeBytesAvailable,
_Out_opt_ PULARGE_INTEGER lpTotalNumberOfBytes,
_Out_opt_ PULARGE_INTEGER lpTotalNumberOfFreeBytes
);GetDiskFreeSpaceEx获取到的数据单位同样为Byte