Translate to:

Delphi File Management Routines

Delphi comes with a number of file routines, defined in the SysUtils Unit, to help you work with files. In this example, you will learn how to:

  • Read and change File Date and Time Stamps
  • Access and change the File Attributes (Example: Make a file read-only or hidden)
  • Extract the File Name from a path
  • Extract the Directory from a path
  • Extract and change the File Extension
  • Rename and move files
  • Determine and change the current active directory
  • Delete a file
  • Test for a valid file or directory
  • Search for files (or partial file names) recursively from a given path
  • Determine the Date and Time when a file was created
  • Determine the Date and Time when a file was accessed
  • Determine the Date and Time when a file was updated

You will also see an example of recursive coding, populating a StringGrid and using while-you-wait animation. Related to this topic is working with INI files, but I will not be covering this here. Click here for an example of how to use an INI file with your Delphi application.

File Routines using Delphi

Overview of File Routines

I have written a small application to demonstrate many of the file routines that can be used with Delphi. Some of these are very obvious and do not need much explanation. Others are a little more involved but are still quite simple to use. The example you can download with this blog covers all of them. Review the code for more details. Following are some of the simplest routines:

Extracting The Path (includes trailing backslash):

ExtractFilePath (FileName) ;

The function returns a string which will be empty if the file name does not include the drive and directory paths. For example: ExtractFilePath('Test.txt') will return an empty string, but ExtractFilePath('c:\temp\Test.txt') will return "c:\temp\".

Extracting The Directory (excludes trailing backslash):

ExtractFileDir (FileName) ;

The function returns a string which will be empty if the file name does not include the drive and directory paths. For example: ExtractFileDir('Test.txt') will return an empty string, but ExtractFileDir('c:\temp\Test.txt') will return "c:\temp". The resulting string is a directory that can be passed to other functions such as GetCurrentDir.

Extracting The File Name:

ExtractFileName (FileName) ;

The function returns the file name even if the parameter "FileName" does not include the drive and directory paths. For example: ExtractFileName('Test.txt') and ExtractFileName('c:\temp\Test.txt') will both return "Test.txt".

Extracting The File Extension:

ExtractFileExt (FileName) ;

The function returns the extension of a file name. For example: ExtractFileExt('Test.txt') will return ".txt". Note that the period character that separates the name and the extension is included. If the file does not have an extension, the returned string will be empty. So, ExtractFileExt('c:\temp\Test') will return an empty string.

Renaming Or Moving A File:

RenameFile (OldFileName, NewFileName) ;

The function attempts to change the file name from the one specified by "OldFileName" to that of "NewFileName". For example, the code that will rename the file "Test.txt" to "Hello.txt", is RenameFile('c:\Test.txt', 'c:\Hello.txt'). If the operation succeeds, the fuction returns True. If it fails, it returns False.

If you specify a new file path as part of the new name, the file will also be moved. For example, RenameFile('c:\Test.txt', 'd:\'Hello.txt') will rename the file "Test.txt" to "Hello.txt" and move it from "c:\" to "d:\".

Under Windows, if the new file name represents an existing file, the operation will fail. But, under Linux, it gets overwritten without warning.

Changing The File Extension:

NewFileName := ChangeFileExt (FileName, NewExtension) ;

RenameFile (OldFileName, NewFileName);

The function "ChangeFileExt" does not actually rename the file with a new extension. It just creates a new file name string using the new extension. You will then need to call the "RenameFile" function to rename the actual file. When you specify a new extension, include the preceding period. Otherwise, as an example, ChangeFileExt('Mary.bmp', 'jpg') will result in "Maryjpg" instead of "Mary.jpg".

Determining If A File Or Directory Exists:

FileExists(FileName);

DirectoryExists(Directory);

FileExists returns True if the file name specified by "FileName" exists. Otherwise, it returns False. Similarly, DirectoryExists returns True if the directory exists and False if it does not.

Deleting A File:

DeleteFile(FileName);

The function DeleteFile deletes the file specified by "FileName". If it succeeds, it returns True. If it does not succeed for whatever reason (file does not exist, is set to read-only, no permission), it returns False.

Determining The Current Directory:

GetCurrentDir() ;

It is important to note that if you do not specify the full path as part of a file name, you may get unexpected results. For example, the code RenameFile ('C:\Test.txt', 'Hello.txt') can give you trouble. You may expect to find the file "Hello.txt" under "C:\" after the code executes, but this may not be the case. If, for example, the current directory in memory is set to "D:\MyDocuments\letters", the file "Test.txt" will be renamed to "Hello.txt" and then moved to "D:\MyDocuments\letters."

To determing the current directory, use the function GetCurrentDir.

Setting The Current Directory:

SetCurrentDir(Directory);

To change the current directory to a different one, use the function SetCurrentDir. For example:

if GetCurrentDir <> 'C:\Pictures' then SetCurrentDir('C:\Pictures') ;

The above code will evaluate the current directory, and make sure that it is set to "C:\Pictures". If it succeeds, it returns True. Otherwise, it returns False.

Finding The Date-Time Stamp Of A File:

To get the OS timestamp of a file, use the function FileAge. You can then convert the returned value (an integer) to a TDateTime object by using the FileDateToDateTime function. If the file does not exist, FileAge returns -1. (Note: Under Linux, -1 is a valid timestamp. Use FileExists to verify whether a file exists or not.)

FileDate := FileAge(FileName);

// FileAge returns the file stamp as an integer

eDateTime.Text := DateTimeToStr(FileDateToDateTime(FileDate));

// FileDateToDateTime converts the integer value
// returned by FileAge to a TDateTime object.
// We then use DateTimeToStr to convert it to string

Changing The Date-Time Stamp Of A File:

The following function changes the OS date-time stamp of a file.

Use FileOpen to open a file and obtain its handle and fmOpenWrite to define the access mode. If the return value is 0 or greater, the function is successful. A return of -1 indicates an error.

FileSetDate sets the OS timestamp of the specified file to the value specified by newDateTime. The DateTimeToFileDate function is used to convert the TDateTime value to an OS timestamp. "X" is the Windows file handle of the file to alter. The return value is zero if the function is successful. Otherwise the return value is an error code.

FileClose closes the file given the handle obtained previously by FileOpen.

function TfrmMain.ChangeFileDateTime(Filename: String; newDateTime: TDateTime): Boolean;
var

X : Integer;
begin
X := FileOpen(Filename, fmOpenWrite);
if X = -1 then Result := False
else
begin
FileSetDate(X, DateTimeToFileDate(newDateTime));
FileClose(X);
Result := True;
end;
end;

Call the above function by passing the FileName and the NewDateTime:

ChangeFileDateTime(FileName, NewDateTime);

 

Finding The File Attributes Of A File:

Use FileGetAttr to get the attributes of a given file. This is returned as a string of bits. A return value of -1 indicates an error.

Attributes := FileGetAttr(FileName) ;
// Attributes is defined as an integer variable


Constant Value Description
 
faReadOnly $00000001
Read-Only
faHidden $00000002
Hidden
faSysFile $00000004
System
faVolumeID $00000008
Volume ID
faDirectory $00000010
Directory
faArchive $00000020
Archived
faAnyFile $0000003F
Any

Examples:

if Attributes and faReadOnly > 0 then ShowMessage('File is read only')
else ShowMessage('File is not read only');


if Attributes and faReadOnly = faReadOnly then ShowMessage('File is read only')
else ShowMessage('File is not read only');


if Attributes and $1 <> 0 then ShowMessage('File is read only')
else ShowMessage('File is not read only');

In our example, we have:

chkReadOnly.Checked := Attributes and faReadOnly = faReadOnly ;

If "Attributes and faReadOnly = faReadOnly" evaluates to "True", then "chkReadOnly" checkbox will be checked. Otherwise, it will be unchecked.

Setting & Removing File Attributes Of A File:

Use FileSetAttr to set the attributes of a given file. If it succeeds, it returns 0. In the following examples, "Attributes" is an integer variable that equals to FileGetAttr(FileName).

Examples:

if FileSetAttr ('c:\Test.txt', Attributes or faReadOnly) = 0 then ShowMessage ('c:\Test.txt set to READ-ONLY')
else ShowMessage ('Setting attributes FAILED!');


if FileSetAttr ('c:\Test.txt', Attributes or $01 or $02) = 0 then ShowMessage ('c:\Test.txt set to READ-ONLY and HIDDEN')
else ShowMessage ('Setting attributes FAILED!');

You would also use FileSetAttr to remove an attribute. Example:

if FileSetAttr ('c:\Test.txt', Attributes xor faReadOnly) = 0 then ShowMessage ('c:\Test.txt is no longer Read-Only')
else ShowMessage ('Removing Read-Only Attribute FAILED!');

 

Searching For Files Recursively:

The RecursiveFileSearch procedure in our example searches recursively for a specified file name (or a portion of a name - wildcards are accepted) in a given root folder and then populates a StringGrid with the following information:

  1. The full path of a matching file name
  2. The file size
  3. The file attributes
  4. The date and time the file was created
  5. The date and time the file was last modified
  6. The date and time the file was last accessed
  7. The time it takes to complete the search

The code is documented, so download the project and go through the steps. Note the following:

  • The TSearchRec type defines file information searched for by a FindFirst or FindNext function call. If a file is found, the fields of the TSearchRec type parameter are modified to specify the found file.
  • FindFirst searches the specified directory for the first file that matches the file name and attributes. Use the fields of this search record to extract the information needed. FindFirst returns 0 if a file was successfully located, otherwise, it returns an error code.
  • FindNext returns the next entry that matches the name and attributes specified in a previous call to FindFirst. The return value is zero if the function was successful. Otherwise the return value is an error code.
  • FindFirst allocates resources (memory) which must be released by calling FindClose.
  • The function FileTimeToDateTime allows us to convert the values ftCreationTime, ftLastWriteTime and ftLastAccessTime to display in our grid.

Speeding Up Your Search & While-You-Wait Animation

In my example, I populate a StringGrid with the results of the file search. I also show an example of how to use TAnimate to display a common AVI file during the search ("while-you-wait" animation). Hiding the grid before the search and showing it after the search can considerably speed up your search. In my case, for example, searching recursively for all DLL files under Windows was done in half the time when the StringGrid was hidden. See below for details.

With the StringGrid visible during the file search:

file management routines using delphi

With the StringGrid hidden during the file search:

file management


The above was an overview of file management using Delphi. In our classes, we cover this in detail and also go over additional training, such as streaming files, breaking up files and restructuring them, and working with different file types.

Please contact us to find out more about our Online Delphi Classes. If you need consulting services, please call us at +1 678-921-0644 or visit us online at:

http://www.onlinedelphitraining.com/


Online Delphi Training

Learn LIVE
From The Comfort Of Your Home
Start Immediately!

+1 (678) 921-0644


Do you have any comments about this topic?

Click on: Post Comments/Questions

To download the project click on: Delphi File Routines

Online Delphi Training


©2005-2008 Business-IQ file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi
file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,
file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi,file routines,file management,Delphi training,files,delphi