Windows 如何查找系统上所有磁盘的驱动器号?
我想在系统的所有磁盘上搜索一个文件。我已经知道如何在单个磁盘上搜索这个问题: 我把它当作Windows 如何查找系统上所有磁盘的驱动器号?,windows,delphi,winapi,Windows,Delphi,Winapi,我想在系统的所有磁盘上搜索一个文件。我已经知道如何在单个磁盘上搜索这个问题: 我把它当作 function TMyForm.FileSearch(const dirName: string); ... FileSearch('C:'); 我不知道如何使用它查找所有可用驱动器号(C、D、E等)上的文件。如何查找这些可用驱动器号的列表?您只需获取可用驱动器的列表,并通过调用函数循环它们即可 在Delphi的最新版本中,您可以使用它轻松检索所有驱动器号的列表 uses System.Type
function TMyForm.FileSearch(const dirName: string);
...
FileSearch('C:');
我不知道如何使用它查找所有可用驱动器号(C、D、E等)上的文件。如何查找这些可用驱动器号的列表?您只需获取可用驱动器的列表,并通过调用函数循环它们即可 在Delphi的最新版本中,您可以使用它轻松检索所有驱动器号的列表
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函数。它的使用要复杂得多,但这里有一些代码可以为您包装它。(在uses子句中需要Windows、SysUtils和类型。)
除了查找此代码之外,您还尝试了什么?您需要首先获取所有磁盘的列表,然后遍历该列表。当然你不是第一个这样做的人…在外循环中使用。它们的工作原理类似于
FindNextFile
和friends。最初的问题也让我感到困惑。我认为OP的代码与此无关。OP可能会提到,他已经知道如何在单个驱动器中搜索文件,并具有相应的功能。但需要搜索所有系统驱动器。我认为,至少函数的增量和他如何使用它使问题和答案更有用,因为人们不必按照链接来理解它。但请记住,可能有一些卷没有指定驱动器号。(在大多数情况下,可以忽略它们。)@Harry:是的,但问题特别要求所有磁盘的驱动器号。
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;