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
www.delphiinformant.com/features/2000/05/di200005sm_f/di200005sm_f.asp 

Active Directory Service Interfaces
www.agnisoft.com/adsi/Conf2000/3132.htm 

 
Adding or removing the backslash from a path http://members.xoom.com/_XOOM/jescott/DelphiCodeTips1.html#BackSlash
In D5, use ExcludeTrailingBackSlash and IncludeTrailingBackSlash functions.
 
Application's directory path ExtractFilePath(Paramstr(0));  
Browse

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.
http://delphi.icm.edu.pl/ftp/d20free/dirmon.zip 

TChangeMonitor component can watch Microsoft Windows' special folders.  www.fortunecity.com/skyscraper/download/125/delphi.html#TChangeMonitor

Direcory Changes Monitoring Component.  You will be notified by all inserted, deleted, modified and renamed files or subdirs in a directory.
http://delphi.icm.edu.pl/ftp/d40free/phDirMon.zip 

 
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
http://members.xoom.com/_XOOM/jescott/DelphiCodeTips1.html#CopyAllFiles

 
CountFiles see example below in FindFirst/FindNext  
CountFolders see example below in FindFirst/FindNext  
CRC
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
http://members.xoom.com/_XOOM/jescott/DelphiCodeTips1.html#DeleteAllFiles

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)

DirSize
http://members.xoom.com/_XMCM/jescott/DelphiCodeTips2.html#DirSize

See:
- GetFolderSize 
- FileCheck utility

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

See:
- Example under Append in File I/O

FileCtrl
DirNotify DirNotify component monitors a directory for changes in its  files and/or sub-directories.  ftp://carlos.123webhosting.net/pub/dirnotify.zip  
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.
http://delphi.icm.edu.pl/ftp/d40free/drivedir.zip
 
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.
http://delphi.icm.edu.pl/ftp/d40free/diskvisr.zip
 
ExcludeTrailing
BackSlash
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.

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

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

SysUtils
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.

See:

- 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:  http://www.merlyn.demon.co.uk/programs/dirslist.pas

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 '*.*'
FUNCTION CountFiles (CONST Path: STRING; CONST FileSpec: STRING): INTEGER;
  VAR
    ReturnCode : INTEGER;
    SearchRec : TSearchRec;
BEGIN
  RESULT := 0;
  ReturnCode := SysUtils.FindFirst(Path + '\' + 
                  Filespec, faAnyFile, SearchRec);
  TRY
    WHILE ReturnCode = 0 DO
    BEGIN
      IF (SearchRec.Attr AND faDirectory <> faDirectory) AND
         (SearchRec.Name <> '.') AND
         (SearchRec.Name <> '..')
      THEN INC (RESULT);
      ReturnCode := SysUtils.FindNext(SearchRec)
    END;
  FINALLY
    SysUtils.FindClose(SearchRec)
  END
END {CountFiles};
// Count subfolders (subdirectories) in given directory
FUNCTION CountFolders(CONST Path: STRING): INTEGER;
  VAR
    ReturnCode: INTEGER;
    SearchRec : TSearchRec;
BEGIN
  RESULT := 0;
  ReturnCode := SysUtils.FindFirst(Path + '\*.*',
                  faDirectory, SearchRec);
  TRY
    WHILE ReturnCode = 0 DO
    BEGIN
      IF (SearchRec.Attr AND faDirectory > 0) AND
         (SearchRec.Name <> '.') AND
         (SearchRec.Name <> '..')
      THEN INC (RESULT);
      ReturnCode := SysUtils.FindNext(SearchRec)
    END;
  FINALLY
    SysUtils.FindClose(SearchRec);
  END
END {CountFolders};
// Also see, Borland FAQ 777D
FUNCTION DeleteFolder(CONST Folder: TFileName): BOOLEAN;
  VAR
    OK        : BOOLEAN;
    ReturnCode: INTEGER;
    SearchRec : TSearchRec;
BEGIN
  RESULT := TRUE;
  ReturnCode := SysUtils.FindFirst(Folder + '\*.*',
                  faAnyFile, SearchRec);
  TRY
    WHILE ReturnCode = 0 DO
    BEGIN
      IF (SearchRec.Name <> '.') AND
         (SearchRec.Name <> '..') AND
         (SearchRec.Attr <> faDirectory)
      THEN BEGIN
        OK := SysUtils.DeleteFile(Folder + '\' +
              SearchRec.Name);
        IF   NOT OK
        THEN RESULT := FALSE;
      END;
      ReturnCode := SysUtils.FindNext(SearchRec);
    END;
  FINALLY
    SysUtils.FindClose(SearchRec);
  END;
  RESULT := RemoveDir(Folder) AND RESULT;
END {DeleteFolder};
PROCEDURE GetFolderSize
         
(CONST Path: STRING;  VAR TotalBytes: Integer;
           VAR TotalFiles: INTEGER);
  VAR
    SearchRec : TSearchRec;
    ReturnCode: INTEGER;
BEGIN
  TotalBytes := 0;
  TotalFiles := 0;

  ReturnCode := SysUtils.FindFirst(Path + '\*.*', 
                  faAnyFile, SearchRec);
  WHILE ReturnCode = 0 DO
  BEGIN
    IF  (SearchRec.Name <> '.') AND
        (SearchRec.Name <> '..') AND
        (SearchRec.Attr <> faDirectory)
    THEN BEGIN
      TotalBytes := TotalBytes + SearchRec.Size;
      TotalFiles := TotalFiles + 1;
    END;
    ReturnCode := SysUtils.FindNext(SearchRec);
  END;
  SysUtils.FindClose(SearchRec)
END {GetFolderSize};
SysUtils
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
www.preview.org/q/q1022.shtml

 
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
www.preview.org/q/q1016.shtml
 
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)

SysUtils
RenameFile function RenameFile(const OldName, NewName:   string):  Boolean;
Renames the specified file or directory.  Wrapper around MoveFile API call.
SysUtils
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. http://inner-smile.com/dl_res.htm  
RmDir Recursive delete a group of files and subdirectories
www.preview.org/q/q1016.shtml
System
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.
www.richplum.co.uk/downloads/dbe/selectdir.zip

Also see SHBrowseForFolder

FileCtrl
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
http://members.nbci.com/_XMCM/ray_adams/components.htm 

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.  www.programmersheaven.com/zone2/cat60/14478.htm 

Demonstrate how to implement a browse for folders dialog using SHBrowseForFolder.
www.ecnet.net/users/gsmpati/delphi

PBFolderDialog is SHBrowseForFolder dialog with capability of creating new folders when browsing for a folder.  http://delphi.icm.edu.pl/ftp/d20free/PBFolder.zip 

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 di9904kb.zip at www.delphizine.com/download/default.asp

Also see SelectDirectory

ShellAPI
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
http://www.delphi-jedi.org/Jedi:APILIBRARY 
ftp://delphi-jedi.org/api/ShFolder.zip 
 
SHGetSpecialFolderLocation Opening the "Find Files..." Dialog Using Delphi
www.undu.com/Articles/980226a.htm
 
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.  http://delphi.icm.edu.pl/ftp/d50free/spfolder.zip  
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
www.gdsoft.com/swag/dirs.zip    (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.   http://delphi.icm.edu.pl/ftp/d20free/ftree.zip  
bookmark.gif (183 bytes)TSearchRec Used in FindFirst/FindNext

TSearchRec =
record
  Time: Integer;
  Size: Integer;
  Attr: Integer;
  Name: TFileName;
  ExcludeAttr: Integer;
  FindHandle : THandle;
  FindData   : TWin32FindData;
end;
 
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.
http://delphi.icm.edu.pl/ftp/d30free/shltree.zip
 
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:
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User
shell folders

 

Updated
27 Aug 2005


since
19 Apr 1999