【问题标题】:How can I find the drive letters for all disks on a system?如何找到系统上所有磁盘的驱动器号?
【发布时间】:2016-08-30 02:14:35
【问题描述】:

我想在系统的所有磁盘上搜索一个文件。从这个问题我已经知道如何在单个磁盘上搜索:How to Search a File through all the SubDirectories in Delphi

我把它当作

function TMyForm.FileSearch(const dirName: string);

...

FileSearch('C:');

我不知道如何使用它来查找所有可用驱动器号、C、D、E 等上的文件。如何找到这些可用驱动器号的列表?

【问题讨论】:

  • 除了找到此代码之外,您还尝试了什么?
  • 您需要首先获取所有磁盘的列表,然后遍历该列表。你肯定不是第一个这样做的人......
  • 在外循环中使用FindFirstVolume, FindNextVolume and FindCloseVolume。他们的工作方式与FindNextFile 和朋友类似。
  • 最初的问题也让我感到困惑。我认为 OP 的 code 在这里不相关。 OP 可能会提到他已经知道如何在单个驱动器中搜索文件并具有相应的功能。但需要搜索所有系统驱动器。
  • 我认为至少函数的声明和他如何使用它使问题和答案更有用,因为人们不必点击链接来理解它。

标签: windows delphi winapi


【解决方案1】:

您可以只获取可用驱动器的列表,然后通过它们循环调用您的函数。

在最新版本的 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。它的使用要复杂得多,但是这里有一些代码可以为您包装它。 (您的 uses 子句中需要 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;

【讨论】:

  • 但请记住,可能存在未分配驱动器号的卷。 (在大多数情况下,可以忽略它们。)
  • @Harry:是的,但这个问题专门询问所有磁盘的驱动器号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 2021-11-12
  • 2014-12-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-29
  • 2011-04-26
相关资源
最近更新 更多