How to Work With Files And File Handling In Delphi?

10 minutes read

Working with files and file handling in Delphi involves performing various operations on files such as creating, opening, reading, writing, and closing files. Delphi provides a set of components, functions, and procedures to handle file operations efficiently. Here are some important concepts and techniques involved in working with files in Delphi:

  1. File Handling Units: Delphi includes several units that assist in file handling, such as System.SysUtils, System.IOUtils, and System.Classes. These units provide classes, functions, and procedures to manipulate files.
  2. File Variables: File variables in Delphi act as references to files. They are declared using the File type or an equivalent file type provided by the unit. Each file variable represents a particular file that can be accessed using procedures and methods.
  3. Opening and Closing Files: Before accessing a file, it needs to be opened for reading, writing, or both. The AssignFile procedure is used to associate a file variable with a specific file. The Reset procedure opens a file for reading, while Rewrite opens a file for writing. After the file operations are completed, the CloseFile procedure should be used to close the file.
  4. Reading from Files: To read data from a file, the Read function or ReadLn procedure is used. Read reads data directly into variables, while ReadLn reads a line of text. When reading from a file, it is essential to check the EndOfFile function to avoid reading beyond the end of the file.
  5. Writing to Files: To write data to a file, the Write and WriteLn procedures are used. Write writes data directly from variables, while WriteLn writes a line of text. Files can be written in various formats, including text, binary, or custom-defined formats.
  6. File Positioning: The FilePos function returns the current position within a file. To modify the position within a file, the Seek and SeekEof procedures can be used. Seek sets the file position to a specified position, while SeekEof moves the file position to the end of the file.
  7. File Attributes and Information: Delphi provides functions to extract useful information about files, such as their size, timestamp, attributes, and whether they exist. Functions like FileSize, FileDate, and FileExists can assist in dealing with file attributes.
  8. File Manipulation: Delphi enables file handling operations like copying, moving, renaming, deleting, and creating directories. Classes such as TFile and TDirectory in System.IOUtils offer methods to perform these operations efficiently.


It is important to handle file exceptions and errors during file handling operations to avoid crashes or incorrect behavior. Exception handling mechanisms, such as try-except blocks, can be used to manage potential errors during file processing.

Best Borland Delphi Books to Read in 2024

1
Delphi Cookbook: Recipes to master Delphi for IoT integrations, cross-platform, mobile and server-side development, 3rd Edition

Rating is 5 out of 5

Delphi Cookbook: Recipes to master Delphi for IoT integrations, cross-platform, mobile and server-side development, 3rd Edition

2
Delphi Programming for Dummies

Rating is 4.9 out of 5

Delphi Programming for Dummies

3
The Little Book Of Delphi Programming: Learn To Program with Object Pascal (Little Programming Books)

Rating is 4.8 out of 5

The Little Book Of Delphi Programming: Learn To Program with Object Pascal (Little Programming Books)

4
Mastering Borland Delphi: A Comprehensive Guide

Rating is 4.7 out of 5

Mastering Borland Delphi: A Comprehensive Guide

5
Borland Delphi Second Edition

Rating is 4.6 out of 5

Borland Delphi Second Edition

6
Delphi GUI Programming with FireMonkey: Unleash the full potential of the FMX framework to build exciting cross-platform apps with Embarcadero Delphi

Rating is 4.5 out of 5

Delphi GUI Programming with FireMonkey: Unleash the full potential of the FMX framework to build exciting cross-platform apps with Embarcadero Delphi


How to get the file extension in Delphi?

In Delphi, you can use the ExtractFileExt function from the SysUtils unit to get the file extension. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
uses
  SysUtils;

var
  filePath, fileExt: string;
begin
  filePath := 'C:\path\to\file.txt';
  fileExt := ExtractFileExt(filePath);
  // fileExt now contains '.txt'
end;


The ExtractFileExt function returns the file extension including the dot (.), so you can use it directly if you need the file extension with the dot. If you want to remove the dot, you can use the Delete function, like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
uses
  SysUtils;

var
  filePath, fileExt: string;
begin
  filePath := 'C:\path\to\file.txt';
  fileExt := ExtractFileExt(filePath);
  Delete(fileExt, 1, 1);
  // fileExt now contains 'txt'
end;


In this example, the Delete function is used to remove the first character (dot) from the file extension.


How to set a file as read-only in Delphi?

To set a file as read-only in Delphi, you can use the FileSetAttr function in the SysUtils unit. Here's an example of how to do it:

  1. Add the SysUtils unit to your uses clause, if it's not already there.
  2. Use the FileSetAttr function to set the file attribute to read-only. The function takes two parameters: The first parameter is the name of the file you want to set as read-only. The second parameter is the attributes you want to set. In this case, you should use faReadOnly.


Here's an example code snippet that demonstrates how to set a file as read-only:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
uses
  SysUtils;

procedure SetFileAsReadOnly(const FileName: string);
begin
  if not FileExists(FileName) then
  begin
    ShowMessage('File does not exist');
    Exit;
  end;
  
  FileSetAttr(FileName, FileGetAttr(FileName) or faReadOnly);
  ShowMessage('File set as read-only');
end;


In the above example, the SetFileAsReadOnly procedure:

  • First checks if the file exists using FileExists function.
  • Then uses FileSetAttr to set the file attributes by using FileGetAttr to retrieve the current attributes and OR-ing them with faReadOnly.
  • Finally, displays a message indicating that the file has been set as read-only using ShowMessage.


You can call this procedure passing the file name as a parameter to set the file as read-only. For example:

1
SetFileAsReadOnly('C:\path\to\file.txt');


Note: Make sure that your program has sufficient permissions to modify file attributes in the specified location.


How to get the file path in Delphi?

To get the file path in Delphi, you can use the TOpenDialog or TSaveDialog component. Here's an example:

  1. Drop a TOpenDialog component onto your form.
  2. In your code, add the Dialogs unit to the uses clause.
  3. Create an event handler for a button or any other event that will trigger the file selection dialog to open.


Example code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
uses
  Dialogs;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if OpenDialog1.Execute then
  begin
    ShowMessage(OpenDialog1.FileName);
    // Use OpenDialog1.FileName to get the selected file path
  end;
end;


When the user selects a file using the file selection dialog, the FileName property of the TOpenDialog component will contain the full file path, which can be used as needed.


How to read/write Excel files in Delphi?

To read/write Excel files in Delphi, you can use the Microsoft Office Automation objects or third-party libraries such as FlexCel or XLSReadWrite. Here's a step-by-step guide using Microsoft Office Automation:

  1. Make sure that you have Microsoft Excel installed on your computer.
  2. Open your Delphi project or create a new one.
  3. Add the "ComObj" unit to your uses clause to enable COM automation.
  4. Create an instance of the Excel application object using the CreateOleObject or GetActiveOleObject function.
1
2
3
4
5
6
7
8
uses
  ComObj;

var
  ExcelApp: Variant;
begin
  ExcelApp := CreateOleObject('Excel.Application');
end;


  1. Open the Excel file using the Workbooks.Open method.
1
2
3
4
5
6
7
var
  ExcelApp: Variant;
  Workbook: Variant;
begin
  ExcelApp := CreateOleObject('Excel.Application');
  Workbook := ExcelApp.Workbooks.Open('C:\path\to\your\file.xlsx');
end;


  1. Access the worksheet or specific cells to read or modify the data.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
var
  ExcelApp: Variant;
  Workbook: Variant;
  Worksheet: Variant;
  Range: Variant;
begin
  ExcelApp := CreateOleObject('Excel.Application');
  Workbook := ExcelApp.Workbooks.Open('C:\path\to\your\file.xlsx');
  Worksheet := Workbook.Worksheets[1]; // Access the first worksheet

  Range := Worksheet.Range['A1']; // Access a specific cell
  ShowMessage(Range.Value); // Display the cell value

  Range.Value := 'New Value'; // Modify the cell value
  Workbook.Save;

  Workbook.Close;
  ExcelApp.Quit;
end;


  1. Don't forget to release the COM objects when you're done.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var
  ExcelApp: Variant;
  Workbook: Variant;
  Worksheet: Variant;
  Range: Variant;
begin
  ExcelApp := CreateOleObject('Excel.Application');
  Workbook := ExcelApp.Workbooks.Open('C:\path\to\your\file.xlsx');
  Worksheet := Workbook.Worksheets[1];

  // ... your code ...

  Range := Unassigned; // Release the range object
  Worksheet := Unassigned; // Release the worksheet object

  Workbook.Close;
  Workbook := Unassigned; // Release the workbook object

  ExcelApp.Quit;
  ExcelApp := Unassigned; // Release the Excel application object

  CoUninitialize; // Uninitialize COM
end;


Remember to handle any exceptions that might occur during the process and implement proper error handling.


How to get the last modification date of a file in Delphi?

To get the last modification date of a file in Delphi, you can make use of the GetFileDateTime function from the SysUtils unit. Here's an example:

1
2
3
4
5
6
7
uses
  SysUtils;

function GetLastModificationDate(const FileName: string): TDateTime;
begin
  Result := FileDateToDateTime(FileAge(FileName));
end;


You can then call this function with the path to the file you're interested in, and it will return the last modification date as a TDateTime value.

1
2
3
4
5
6
var
  LastModifiedDate: TDateTime;
begin
  LastModifiedDate := GetLastModificationDate('C:\path\to\your\file.ext');
  // Use the LastModifiedDate as needed
end;


Note that the FileAge function returns 0 if the file doesn't exist or if its date information couldn't be retrieved. So, you may want to handle such cases accordingly.

Twitter LinkedIn Telegram Whatsapp

Related Posts:

Multithreading in Delphi refers to the ability to execute multiple threads concurrently within a Delphi application. Implementing multithreading in Delphi can provide several benefits, such as improved performance and responsiveness. Here are the key steps to ...
Error handling in Delphi is the process of managing and dealing with unexpected errors that may occur during the execution of a program. It is important to handle errors properly to ensure the stability and reliability of your application. Here are some key po...
Creating custom components in Delphi allows you to extend the functionality of the IDE by adding new controls that can be used in your applications. Here is a step-by-step guide on how to create custom components in Delphi:Open Delphi and create a new package ...