windows - 如何找到系统上所有磁盘的驱动器号?

标签 windows delphi winapi

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

我用它作为

function TMyForm.FileSearch(const dirName: string);

...

FileSearch('C:');

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

最佳答案

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

在最新版本的 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;

关于windows - 如何找到系统上所有磁盘的驱动器号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39206951/

相关文章:

Python3 utf-8 解码问题

ruby-on-rails - Windows 上的 Ruby on Rails 问题 [msvcrt-ruby18.dll 错误] - 新手问题

c# - Windows 域登录可以包含超过 1 个 '\' 字符吗?

delphi - 如何在名称中带有冒号的表上运行查询?

c++ - visual studio 中的空项目和非空项目有什么区别?

无法将参数 1 从 'const char *' 转换为 'LPCWSTR'

c++ - C++ 中的窗口锁定和解锁事件

delphi - 鼠标悬停(类似提示)delphi

Delphi:右括号可选?

C++ lib查看器下载