DelphiDabbler Code Snippets Database

Snippet Selection

The following snippets from the Code Snippets Database have been requested.

CountFiles

Returns the number of files in the folder specified by APath that match the DOS style wildcard AWildCard. Any sub-directories of APath and the files they contain are not counted.

function CountFiles(const APath, AWildCard: string): Int64;
var
  ReturnCode: Integer;            // result of FindFirst and FindNext routines
  SearchRec: SysUtils.TSearchRec; // carries info about file search
begin
  Result := 0;
  ReturnCode := SysUtils.FindFirst(
    DirToPath(APath) + AWildCard, SysUtils.faAnyFile, SearchRec
  );
  try
    while ReturnCode = 0 do
    begin
      if not IsFlagSet(SearchRec.Attr, SysUtils.faDirectory) and
        (SearchRec.Name <> '.') and
        (SearchRec.Name <> '..') then
        Inc(Result);
      ReturnCode := SysUtils.FindNext(SearchRec);
      ProcessMessages;
    end;
  finally
    SysUtils.FindClose(SearchRec);
  end;
end;

CurentDrive

Returns the letter that identifies the current drive.

function CurentDrive: Char;
var
  Dir: string; // current drive as string
begin
  GetDir(0, Dir);
  Result := Dir[1];
end;

GetParentDirectory

Returns the parent directory of the provided path.

function GetParentDirectory(const APath: string): string;
begin
  Result := SysUtils.ExpandFileName(DirToPath(APath) + '..');
end;

PathIsRoot

Checks if the given path is a root directory.

function PathIsRoot(const APath: string): Boolean;
var
  Idx: Integer;     // index of first backslash in path
  OrgPath: string;  // copy of path being processed
begin
  OrgPath := APath;
  Result := True;
  if Copy(OrgPath, 1, 2) = '\\' then
  begin
    // Path is a UNC path
    Delete(OrgPath, 1, 2);
    Idx := SysUtils.AnsiPos('\', OrgPath);
    if Idx > 0 then
    begin
      Delete(OrgPath, 1, Idx);
      // UNC path has \\server\share only - treat it as root path
      if SysUtils.AnsiPos('\', OrgPath) = 0 then
        Exit;
    end
    else // UNC path has server name only - treat as root path
      Exit;
  end;
  // We get here if UNC path has a folder under the share,
  // or it is a path with a drive specifier.
  OrgPath := DirToPath(APath);
  // Now we check if going up from the path leaves us with the
  // same path
  Result := SysUtils.AnsiSameText(
    SysUtils.ExpandFileName(OrgPath + '..'), OrgPath
  );
end;

View the whole database.

Go to the DelphiDabbler website.