我需要在Delphi程序中获得总磁盘空间。
答案 0 :(得分:9)
使用DiskSize和DiskFree函数解决此问题。 ComboBox1包含驱动器号列表。
var
Disk: Integer;
...
procedure TForm1.Button1Click(Sender: TObject);
var
Total, Free: LongInt;
begin
Total:=DiskSize(Disk) div 1024;
Free:=DiskFree(Disk) div 1024;
Gauge1.MaxValue:=Total;
Gauge1.Progress:=Free;
Label1.Caption:='Total size - '+IntToStr(Total);
Label2.Caption:='Free - '+IntToStr(Free);
end;
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
Disk:=ComboBox1.ItemIndex+1;
end;
答案 1 :(得分:5)
这里有另一个使用Win32_LogicalDisk
WMI类
{$APPTYPE CONSOLE}
uses
SysUtils,
ActiveX,
ComObj,
Variants;
procedure GetWin32_LogicalDiskSize(const drive: string);
const
WbemUser ='';
WbemPassword ='';
WbemComputer ='localhost';
wbemFlagForwardOnly = $00000020;
var
FSWbemLocator : OLEVariant;
FWMIService : OLEVariant;
FWbemObjectSet: OLEVariant;
FWbemObject : OLEVariant;
oEnum : IEnumvariant;
iValue : LongWord;
begin;
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword);
FWbemObjectSet:= FWMIService.ExecQuery(Format('SELECT * FROM Win32_LogicalDisk Where Caption=%s',[QuotedStr(drive)]),'WQL',wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
if oEnum.Next(1, FWbemObject, iValue) = 0 then
begin
Writeln(Format('FreeSpace %s Bytes',[FormatFloat('#,',FWbemObject.FreeSpace)]));// Uint64
Writeln(Format('Size %s Bytes',[FormatFloat('#,',FWbemObject.Size)]));// Uint64
FWbemObject:=Unassigned;
end;
end;
begin
try
CoInitialize(nil);
try
GetWin32_LogicalDiskSize('C:');
finally
CoUninitialize;
end;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln('Press Enter to exit');
Readln;
end.
答案 2 :(得分:1)
有些人可能觉得这很有用 - 它会通过Volume的DeviceID为您提供总磁盘空间和可用磁盘空间。它也使用WMI,如RRUZ的答案,但它适用于DeviceID,因此它具有相同的优点+它也适用于未配对的设备和驱动程序(或映射到路径)。
procedure DiskSizesFromVolumeDeviceID(deviceID:string);
var
WMIServices : ISWbemServices;
Root : ISWbemObjectSet;
Item: Variant;
i: Integer;
Cap:TCap;
begin
try
WMIServices := CoSWbemLocator.Create.ConnectServer('.', 'root\cimv2','', '', '', '', 0, nil);
Root := WMIServices.ExecQuery(Format('SELECT Capacity, FreeSpace FROM Win32_Volume WHERE DeviceID="%s"', [StringReplace(deviceID, '\', '\\', [rfReplaceAll])]),'WQL', 0, nil);
for i := 0 to Root.Count - 1 do
begin
Item := Root.ItemIndex(i);
TotalSpace := ( Item.Capacity);
FreeSpace := (Item.FreeSpace);
End;
end;