File Handles

The File type represents a handle to an open file on the system. DWScript provides both traditional Pascal-style file I/O and modern stream-based approaches.

High-level Helpers

For most tasks, it is easier to use high-level helper functions from the standard library. These handle opening and closing the file automatically.

  • FileExists(path): Returns true if the file exists.
  • FileRead(path): Reads the entire file into a string.
  • FileWrite(path, text): Writes a string to a file.
  • FileReadLines(path): Reads the file into an array of strings.
if FileExists('config.json') then begin
  var json := FileRead('config.json');
  // ...
end;

Binary File I/O (DataStrings)

For binary data, you typically use ByteBuffer or DataStrings.

The DataString Pattern

Many DWScript functions that accept a "binary" string (like FileWrite or certain network functions) expect a DataString. In this pattern, only the lower byte of each UTF-16 character is processed. To ensure data integrity, always use ByteBuffer for raw binary manipulation and convert to a DataString only when required by the API.

var buffer := ByteBuffer(FileRead('data.bin'));
// ... process buffer ...
FileWrite('data_out.bin', buffer.ToDataString);

Permissions & Safety: File operations are subject to the security restrictions of the environment where the script is running. In web environments, file access is typically restricted to specific directories.

Related Reference

For a complete list of file and directory functions, see the Files API Reference.

On this page