Ora

How Do I Create a Text File in Delphi Code?

Published in Delphi File Operations 6 mins read

Creating a text file in Delphi code involves writing character data to a specified file path. A text file, fundamentally, contains only ASCII (American Standard Code of Information Interchange) characters and therefore lacks any formatting or graphics. These files are simple, highly portable, and widely used for data storage, logging, and configuration.

Delphi offers several robust methods to achieve this, ranging from traditional Pascal file I/O to more modern, object-oriented approaches and convenient utility functions.

Methods for Creating Text Files in Delphi Code

Here are the primary ways to create and write to text files using Delphi code:

1. Traditional Pascal File I/O (AssignFile, Rewrite/Append, Writeln/Write)

This is the oldest and most fundamental method, inherited from standard Pascal. It's straightforward for basic operations but requires manual file management.

Steps:

  1. Declare a TextFile variable: This variable acts as a logical representation of your file.
  2. Assign the file path: Use AssignFile to link your TextFile variable to a physical file on disk.
  3. Open the file:
    • Rewrite(FileVar): Creates a new file. If the file already exists, its contents are cleared.
    • Append(FileVar): Opens an existing file for writing at the end. If the file doesn't exist, it is created.
  4. Write content: Use Write or Writeln to output data to the file. Writeln adds a new line character after the output.
  5. Close the file: Use CloseFile to save changes and release the file handle. This step is crucial to prevent data loss or file corruption.

Example:

procedure CreateSimpleTextFile;
var
  MyFile: TextFile;
  FilePath: string;
begin
  FilePath := 'C:\Temp\MyLogFile.txt'; // Specify your desired path

  AssignFile(MyFile, FilePath);
  try
    // Create or overwrite the file
    Rewrite(MyFile);
    Writeln(MyFile, 'This is the first line.');
    Write(MyFile, 'This is on the second line without a newline.');
    Writeln(MyFile); // Add a newline character
    Writeln(MyFile, 'This is the third line.');

    // Append to the same file
    CloseFile(MyFile); // Close before re-opening for append
    Append(MyFile);
    Writeln(MyFile, 'Appended new content.');
  except
    on E: Exception do
      ShowMessage('Error creating file: ' + E.Message);
  finally
    // Always ensure the file is closed, even if an error occurs
    if FileExists(FilePath) and (IOResult = 0) then // Check if file was opened successfully before closing
      CloseFile(MyFile);
  end;
end;

File Opening Modes:

Mode Description
Rewrite Creates a new file or overwrites an existing one.
Append Opens an existing file for writing at the end, or creates it if it doesn't exist.

2. Using TStreamWriter (Modern and Recommended)

TStreamWriter is part of the System.Classes unit and provides a more object-oriented and flexible way to write text to files, especially when dealing with different character encodings (e.g., UTF-8, ANSI). It also offers better resource management.

Steps:

  1. Declare a TStreamWriter variable:
  2. Create an instance: Pass the file path and optionally the encoding to the TStreamWriter.Create constructor.
  3. Write content: Use sw.WriteLine or sw.Write.
  4. Close the writer: Call sw.Free (or use FreeAndNil) to close the file and release resources. It's best practice to put this in a try..finally block to ensure it's always called.

Example:

uses
  System.SysUtils, System.Classes; // Required units

procedure CreateTextFileWithStreamWriter;
var
  sw: TStreamWriter;
  FilePath: string;
begin
  FilePath := 'C:\Temp\ModernLog.txt'; // Specify your desired path
  sw := nil; // Initialize to nil for safety

  try
    // Create a new file (or overwrite existing) with UTF-8 encoding
    sw := TStreamWriter.Create(FilePath, False, TEncoding.UTF8); // False for overwrite
    sw.WriteLine('This is a line written with TStreamWriter.');
    sw.Write('This continues on the same line.');
    sw.WriteLine(' And this starts a new one.');
    sw.WriteLine('Delphi supports various encodings.');
  except
    on E: Exception do
      ShowMessage('Error creating file with TStreamWriter: ' + E.Message);
  finally
    // Ensure the stream writer is closed and freed
    if Assigned(sw) then
      sw.Free;
  end;
end;

3. Utility Functions (TFile.WriteAllText, TFile.AppendAllText)

For very simple cases where you want to write a single string (or an array of strings) to a file quickly, the TFile class in System.SysUtils provides static utility methods. These methods handle file creation, writing, and closing internally.

Methods:

  • TFile.WriteAllText(Path, Contents, [Encoding]): Writes the specified string to a file. If the file exists, it's overwritten.
  • TFile.AppendAllText(Path, Contents, [Encoding]): Appends the specified string to an existing file. If the file doesn't exist, it's created.
  • TFile.WriteAllLines(Path, Contents, [Encoding]): Writes an array of strings to a file, with each string becoming a new line.

Example:

uses
  System.SysUtils; // Required unit

procedure CreateTextFileWithUtilityFunctions;
var
  FilePath: string;
  ContentToSave: string;
begin
  FilePath := 'C:\Temp\QuickLog.txt';

  try
    // Overwrite the file with a single string
    ContentToSave := 'This is a quick log entry.';
    TFile.WriteAllText(FilePath, ContentToSave);

    // Append another string to the same file
    TFile.AppendAllText(FilePath, sLineBreak + 'Another quick entry appended.');

    // Write multiple lines from an array
    TFile.WriteAllLines('C:\Temp\MultiLineLog.txt', ['First line.', 'Second line.', 'Third line from array.']);
  except
    on E: Exception do
      ShowMessage('Error using TFile utility: ' + E.Message);
  end;
end;

Practical Considerations

File Paths and Error Handling

  • Absolute vs. Relative Paths: Always specify a full (absolute) path (e.g., C:\MyData\file.txt) for clarity and reliability. Relative paths can be unpredictable as they depend on the application's current working directory.
  • Permissions: Ensure your application has the necessary write permissions for the target directory. Writing to system directories (e.g., Program Files) usually requires elevated privileges.
  • Error Handling: Always wrap file operations in try..except..finally blocks.
    • try..except: Catches potential errors (e.g., file not found, access denied) and allows your application to respond gracefully.
    • finally: Guarantees that resources (like file handles) are properly closed and freed, regardless of whether an error occurred.

Character Encoding

While text files contain ASCII characters, modern applications often need to support broader character sets (e.g., characters from different languages).

  • TStreamWriter and TFile functions allow you to specify the TEncoding (e.g., TEncoding.UTF8, TEncoding.Default, TEncoding.ASCII). UTF-8 is generally recommended for modern applications as it supports a wide range of characters while being backward-compatible with ASCII.
  • Traditional Pascal I/O typically uses the system's default ANSI encoding, which can be problematic when dealing with diverse character sets.

By understanding these methods and best practices, you can reliably create and manage text files within your Delphi applications.