我想在系统上的所有磁盘上搜索文件。我已经知道如何从这个问题中搜索单个磁盘:How to Search a File through all the SubDirectories in Delphi
我用它作为
function TMyForm.FileSearch(const dirName: string);
...
FileSearch('C:');
我不知道怎么做是用它来查找所有可用驱动器号,C,D,E等上的文件。如何找到那些可用驱动器号的列表?
答案 0 :(得分:13)
您可以获取可用驱动器的列表,并循环调用您的功能。
在最近的Delphi版本中,您可以使用IOUtils.TDirectory.GetLogicalDrives轻松检索所有驱动器号的列表。
uses
System.Types, System.IOUtils;
var
Drives: TStringDynArray;
Drive: string
begin
Drives := TDirectory.GetLogicalDrives;
for s in Drives do
FileSearch(s);
end;
对于不包含IOUtils的旧版本Delphi,您可以使用WinAPI函数GetLogicalDriveStrings。它使用起来要复杂得多,但是这里有一些代码可以帮助你。 (您的使用条款中需要Windows,SysUtils和Types。)
function GetLogicalDrives: TStringDynArray;
var
Buff: String;
BuffLen: Integer;
ptr: PChar;
Ret: Integer;
nDrives: Integer;
begin
BuffLen := 20; // Allow for A:\#0B:\#0C:\#0D:\#0#0 initially
SetLength(Buff, BuffLen);
Ret := GetLogicalDriveStrings(BuffLen, PChar(Buff));
if Ret > BuffLen then
begin
// Not enough memory allocated. Result has buffer size needed.
// Allocate more space and ask again for list.
BuffLen := Ret;
SetLength(Buff, BuffLen);
Ret := GetLogicalDriveStrings(BuffLen, PChar(Buff));
end;
// If we've failed at this point, there's nothing we can do. Calling code
// should call GetLastError() to find out why it failed.
if Ret = 0 then
Exit;
SetLength(Result, 26); // There can't be more than 26 drives (A..Z). We'll adjust later.
nDrives := -1;
ptr := PChar(Buff);
while StrLen(ptr) > 0 do
begin
Inc(nDrives);
Result[nDrives] := String(ptr);
ptr := StrEnd(ptr);
Inc(ptr);
end;
SetLength(Result, nDrives + 1);
end;