Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the drive letters for all disks on a system?

I want to search for a file on all disks on the system. I already know how to search on a single disk from this question: How to Search a File through all the SubDirectories in Delphi

I use it as

function TMyForm.FileSearch(const dirName: string);

...

FileSearch('C:');

What I do not know how to do is use it to find files on all available drive letters, C, D, E etc. How can I find a list of those available drive letters?

like image 961
marcosbontempo Avatar asked Dec 06 '22 17:12

marcosbontempo


1 Answers

You can just get a list of available drives, and loop through them calling your function.

In recent versions of Delphi you can use IOUtils.TDirectory.GetLogicalDrives to retrieve a list of all drive letters easily.

uses
  System.Types, System.IOUtils;

var
  Drives: TStringDynArray;
  Drive: string
begin
  Drives := TDirectory.GetLogicalDrives;
  for s in Drives do
    FileSearch(s);        
end;

For older versions of Delphi that don't contain IOUtils, you can use the WinAPI function GetLogicalDriveStrings. It's considerably more complicated to use, but here's some code that wraps it for you. (You'll need Windows, SysUtils, and Types in your uses clause.)

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;
like image 190
Ken White Avatar answered Jan 26 '23 00:01

Ken White