Delphi Files, Directories, Disks, I/O
A. Files B. Directories C. Disks/Drives D. File I/O E. Stream I/O F. Port I/O

(bookmark.gif (183 bytes) Bookmark)

Topic Description Unit

Active Directories

Active Directories Using ADSI on Your NT and Windows 2000 Systems 

Active Directory Service Interfaces 

Adding or removing the backslash from a path
In D5, use ExcludeTrailingBackSlash and IncludeTrailingBackSlash functions.
Application's directory path ExtractFilePath(Paramstr(0));  

Also see SHBrowseForFolder and SelectDirectory

Changes Detect Changes in Folder

Small application with source that demonstrates the use of  ReadDirectoryChangesW API function to monitor file operations. 

TChangeMonitor component can watch Microsoft Windows' special folders.

Direcory Changes Monitoring Component.  You will be notified by all inserted, deleted, modified and renamed files or subdirs in a directory. 

Compare Neil Rubenking's PC Magazine utility WMatch32,18 March 1999,
compare directories side-by-side, with complete Delphi source code.  Includes routines MatchAllFiles and MatchDifferentFiles.
bookmark.gif (183 bytes)Copying See SHFileOperation

Copying a directory of a set of files

CountFiles see example below in FindFirst/FindNext  
CountFolders see example below in FindFirst/FindNext  
FileCheck.gif (1195 bytes) Calculate Cyclic Redundancy Code (a meta CRC32) of a directory.
efg's CRC FileCheck Lab Report
CreateDir function CreateDir(const Dir: string): Boolean;
Creates a new directory.
bookmark.gif (183 bytes)Deleting See DeletFolder example below

Deleting a directory and all the directory files, Borland FAQ 777D

Peter Below's UseNet Post with example of how to delete a folder

Deleting a directory or a set of files

See efg's Files page:  Recycle Bin and SHFileOperation

Directories and Drives Delphi 5 Developer's Guide (pp. 380-403) by Teixeria and Pacheco  
Directory Size Peter Haas'  UseNet Post explaining "there are two different values, the sum of all file sizes and the allocated disk size" and how to compute these values

DirInfo:  Simon Patterson's UseNet Post   about size of a directory/folder (ignores size of FAT entry)

GetFileSize using FindFirst in UseNet Post by Freter (determine the file or directory size, recursively)


- GetFolderSize 
- FileCheck utility

bookmark.gif (183 bytes)DirectoryExists function DirectoryExists(Name:  string):   Boolean;
Returns TRUE if specified file exists

- Example under Append in File I/O

DirNotify DirNotify component monitors a directory for changes in its  files and/or sub-directories.  
DirView TDirView displays files and subdirectories of a single directory as listview with shell icons taken from the system imagelist.  It supports file operations like creating, copying, renaming and deleting files and directories, full OLE-drag & drop for files and directories using dragimages, clipboard operations, detecting filesystem changes, displaying the system contextmenu and the system property sheets. Part of Filemanager Toolset.
DiskVisor DiskVisor shows the individual sizes of each subdirectory and files in a directory. This utility can also
be used to explore directories to find the largest on the hard disk.
function ExcludeTrailingBackSlash(const s:   string):  string; SysUtils (D5)
ExtractRelativePath function ExtractRelativePath
     (const BaseName, DestName: string): string;

Returns a file path name relative to the given BaseName. It strips the common path dirs and adds '..\' for each level up from the BaseName path.

ExtractFileDir function ExtractFileDir(const FileName: string): string;
Extracts the drive and directory parts of the given filename.
ExtractFilePath function ExtractFilePath(const Filename:   string):  string;
Extracts the drive and directory parts of the given filename.

- example with INI Files in Files section
- example under Append in File I/O section

Find Folders Eddie Shipman's UseNet Post to use Find Files or Folders Dialog

Also see SelectDirectory and SHBrowseForFolder

bookmark.gif (183 bytes) FindFirst/FindNext/ FindClose see also File Attributes  under Files section
see TSearchRec below

There is a FindClose routine in both the Windows and SysUtils unit that can
cause a problem when the order of units in the "uses" section is not correct.
To avoid this ambiguity (and compile time error), and for consistency, prefix
the "Find" routines with "SysUtils," e.g., SysUtils.FindClose as shown in
the examples below.


- Charles Hacker's UseNet Post with recursive GetFiles example.
- Peter Below's example in a UseNet Post
- Using FindFirst and the WIN_32_FIND_DATA structure, Borland TI 1512D
- Fred's UseNet Post with an example of using WIN_32_FIND_DATA
- Using FindFirst and FindNext to find directories, Borland TI 647D
- GetFileSize using FindFirst in UseNet Post by Freter (determine the file or directory size, recursively)
- Deleting a directory and all the directory files, Borland FAQ 777D
- CountFiles, CountFolders, DeleteFolder, GetFolderSize (below)
(See also Recursive Directory Search)

- Dr. John Stockton's solution:

The FileListLibrary.PAS unit provides a ScanDirectory procedure for a generic way to process a hierarchy of directories and files.    Two callback routines are parameters to ScanDirectory to process each file, and to process the beginning and end of a directory.  The routines ProcessDirectory and ProcessFile in ScreenFileCheck.PAS are the routines used as parameters to ScanDirectory.  See the FileCheck Lab Report for the source code.

// Normally FileSpec is '*.*'
    ReturnCode : INTEGER;
    SearchRec : TSearchRec;
  RESULT := 0;
  ReturnCode := SysUtils.FindFirst(Path + '\' + 
                  Filespec, faAnyFile, SearchRec);
    WHILE ReturnCode = 0 DO
      IF (SearchRec.Attr AND faDirectory <> faDirectory) AND
         (SearchRec.Name <> '.') AND
         (SearchRec.Name <> '..')
      ReturnCode := SysUtils.FindNext(SearchRec)
END {CountFiles};
// Count subfolders (subdirectories) in given directory
    ReturnCode: INTEGER;
    SearchRec : TSearchRec;
  RESULT := 0;
  ReturnCode := SysUtils.FindFirst(Path + '\*.*',
                  faDirectory, SearchRec);
    WHILE ReturnCode = 0 DO
      IF (SearchRec.Attr AND faDirectory > 0) AND
         (SearchRec.Name <> '.') AND
         (SearchRec.Name <> '..')
      ReturnCode := SysUtils.FindNext(SearchRec)
END {CountFolders};
// Also see, Borland FAQ 777D
FUNCTION DeleteFolder(CONST Folder: TFileName): BOOLEAN;
    OK        : BOOLEAN;
    ReturnCode: INTEGER;
    SearchRec : TSearchRec;
  ReturnCode := SysUtils.FindFirst(Folder + '\*.*',
                  faAnyFile, SearchRec);
    WHILE ReturnCode = 0 DO
      IF (SearchRec.Name <> '.') AND
         (SearchRec.Name <> '..') AND
         (SearchRec.Attr <> faDirectory)
        OK := SysUtils.DeleteFile(Folder + '\' +
        IF   NOT OK
      ReturnCode := SysUtils.FindNext(SearchRec);
  RESULT := RemoveDir(Folder) AND RESULT;
END {DeleteFolder};
(CONST Path: STRING;  VAR TotalBytes: Integer;
           VAR TotalFiles: INTEGER);
    SearchRec : TSearchRec;
    ReturnCode: INTEGER;
  TotalBytes := 0;
  TotalFiles := 0;

  ReturnCode := SysUtils.FindFirst(Path + '\*.*', 
                  faAnyFile, SearchRec);
  WHILE ReturnCode = 0 DO
    IF  (SearchRec.Name <> '.') AND
        (SearchRec.Name <> '..') AND
        (SearchRec.Attr <> faDirectory)
      TotalBytes := TotalBytes + SearchRec.Size;
      TotalFiles := TotalFiles + 1;
    ReturnCode := SysUtils.FindNext(SearchRec);
END {GetFolderSize};
ForceDirectories see example under "Append" in File I/O section FileCtrl
GetCurrentDir function GetCurrentDir: string; SysUtils
GetDir   System
GetFolderSize see example above in FindFirst/FindNext  
GetSpecialPath See Neil Rubenking's AllFuncs.pas unit in his ColorClue PC Magazine utility.  
GetSystemDirectory Rudy Velthuis' (Team B) UseNet Post with example

Bill Todd's UseNet Post

GetTempFileName Can be used for temporary directory name  
GetTempPath Serghiy Perevoznyk's UseNet Post  
bookmark.gif (183 bytes)GetWindowsDirectory Rudy Velthuis' (Team B) UseNet Post with example

A tricky way to use SetLength

IncludeTrailingBackSlash function IncludeTrailingBackSlash(const s:   string):  string; SysUtils (D5)
JEDI ProjectJediButton.gif (3350 bytes) Delphi Jedi Code Library, JclFileUtils.PAS unit  
Managing Directories Delphi in a Nutshell,  p. 500  
MkDir   System
Path to DOS Path Mayakron's UseNet Post with PathToDOSPath function  
PIDLs Delphi Informant's The Secret World of PIDLs -- Working with Windows' Shell Item Identifiers  
Recursive Search/Delete Recursive delete a group of files and subdirectories
Recycle Bin See efg's Files page:  Recycle Bin and SHFileOperation  
RemoveDir function RemoveDir(const Dir: string): Boolean;

See "DeleteFolder" Example under FindFirst/FindNext/FindClose (above)

RenameFile function RenameFile(const OldName, NewName:   string):  Boolean;
Renames the specified file or directory.  Wrapper around MoveFile API call.
Resource Grabber The Resource-Grabber will scan the directories and drives on your computer and extract all Bitmaps, Glyphs (button images), Icons, Cursors, JPG/JPEG images, WAVE and RMI sound files as well as AVI video clips it finds inside the programs and DLL files in any directory of your choice.  
RmDir Recursive delete a group of files and subdirectories
bookmark.gif (183 bytes) SelectDirectory SelectDirectory brings up a dialog to allow the user to enter a directory name.

Display the Windows directory browser. The Caption parameter specifies a caption for the dialog. The Root parameter specifies the root directory from which to browse. The selected directory is returned as the Directory parameter.
function SelectDirectory(const Caption: string; const Root: WideString; out Directory: string): Boolean; overload;

Call the Select Directory dialog box. The directory passed to the function with the Directory parameter appears as the currently selected directory when the dialog box appears. The name of the directory the user selects becomes the value of Directory when the function returns. The dialog does not change the value of the current directory.
function SelectDirectory(var Directory: string; Options: TSelectDirOpts; HelpCtx: Longint): Boolean; overload;

Example showing how to use the SelectDirectory function with its select directory dialog by Damon Matthews.

Also see SHBrowseForFolder

SetCurrentDir function SetCurrentDir(const Dir: string): Boolean; SysUtils
SetWorkingDirectory Borland's "Adding shortcuts"  TI 1597D  
bookmark.gif (183 bytes) SHBrowseForFolder ScreenBrowseForFolder.jpg (12846 bytes)
efg's BrowseForFolder demo project that includes a way to set the initial folder for the search tree.   Includes info about the FreePIDL API call in Shell32.DLL.

Mike Lischke's UseNet Post with a BrowseCallbackProc function to set the initial path

Lawrence Thurman's UseNet Post with SHBrowseForFolder example

John Scalco's UseNet Post about using BFFM_SETSELECTION message to set the initial directory

Ray Adam's Browse for folder v 2.0 

The Delphi Expert's UseNet Post about how to browse for a folder

"Browsing for Folders" in From the Shell:  Part I: Dialog Boxes You’ve Always Needed, Delphi Informant, April 1999

TBrowseFolder Component Native Delphi component that encapsulates the SHBrowseForFolder interface. 

Demonstrate how to implement a browse for folders dialog using SHBrowseForFolder.

PBFolderDialog is SHBrowseForFolder dialog with capability of creating new folders when browsing for a folder. 

Using the Shell API function SHBrowseForFolder, Borland FAQ 2008D

"From the Shell:  Dialog Boxes You've Always Needed"
Delphi Informant, April 1999, Vol. 5, No. 4, pp. 8-22
File at

Also see SelectDirectory

bookmark.gif (183 bytes)SHFileOperation See efg's Files page:  Recycle Bin and SHFileOperation  
SHFolder ProjectJediButton.gif (3350 bytes)  Extra Shell Folder locations interface by Rudolph Velthuis 
SHGetSpecialFolderLocation Opening the "Find Files..." Dialog Using Delphi
Special Folders The TSpecialFolders component retrieves the location of windows   special folders. This component uses the official Microsoft way  to retrieve the informations about the special folders. This is  the use of the API function SHGetSpecialFolderLocation instead  of reading the information from the windows registry.  
subst Howard Moon's UseNet Post describing a "DOS" way to assign a drive letter to a directory  
SWAG Directory SWAG (Software Archive Group).  59 various directory examples    (requires Reader)
TFolderTree TFolderTree is a folder tree display, similar to the left pane of Windows Explorer, for use with Delphi 2. Now works with Windows NT and includes access to Network Neighborhood.  
bookmark.gif (183 bytes)TSearchRec Used in FindFirst/FindNext

TSearchRec =
  Time: Integer;
  Size: Integer;
  Attr: Integer;
  Name: TFileName;
  ExcludeAttr: Integer;
  FindHandle : THandle;
  FindData   : TWin32FindData;
TShellTree TShellTree is an exact copy of of the Explorer's left pane.    Features: Userdefined Root (Pathes and System-Elements),  Browsing and masking files, automatic Tree-update.
WIN_32_FIND_DATA Using FindFirst and the WIN_32_FIND_DATA structure, Borland TI 1512D

Fred's UseNet Post with an example of using WIN_32_FIND_DATA

Windows Directory See GetWindowsDirectory

Start Menu location is in Registry:
shell folders


27 Aug 2005

19 Apr 1999