Skip to main content
Version: 20 R10

File

File objects are created with the File command. They contain references to disk files that may or may not actually exist on disk. For example, when you execute the File command to create a new file, a valid File object is created but nothing is actually stored on disk until you call the file.create( ) function.

Example

The following example creates a preferences file in the project folder:

var $created : Boolean
$created:=File("/PACKAGE/SpecialPrefs/"+Current user+".myPrefs").create()

Pathnames

File objects support several pathnames, including filesystems or posix syntax. Supported pathnames are detailed in the Pathnames page.

File object
































4D.File.new()

History
ReleaseChanges
18 R6Added

4D.File.new ( path : Text { ; pathType : Integer } ) : 4D.File
4D.File.new ( fileConstant : Integer ) : 4D.File

Description

The 4D.File.new() function creates and returns a new object of the 4D.File type. It is identical to the File command (shortcut).

It is recommended to use the File shortcut command instead of 4D.File.new().

.create()

History
ReleaseChanges
17 R5Added

Not available for ZIP archives

.create()* : Boolean

ParameterTypeDescription
ResultBoolean<-True if the file was created successfully, false otherwise

Description

The .create() function creates a file on disk according to the properties of the File object.

If necessary, the function creates the folder hierachy as described in the platformPath or path properties. If the file already exists on disk, the function does nothing (no error is thrown) and returns false.

Returned value

  • True if the file is created successfully;
  • False if a file with the same name already exists or if an error occured.

Example

Creation of a preferences file in the database folder:

 var $created : Boolean
$created:=File("/PACKAGE/SpecialPrefs/"+Current user+".myPrefs").create()

.createAlias()

History
ReleaseChanges
17 R5Added

.createAlias*( destinationFolder : 4D.Folder ; aliasName : Text { ; aliasType : Integer } ) : 4D.File

ParameterTypeDescription
destinationFolder4D.Folder->Destination folder for the alias or shortcut
aliasNameText->Name of the alias or shortcut
aliasTypeInteger->Type of the alias link
Result4D.File<-Alias or shortcut file reference

Description

The .createAlias() function creates an alias (macOS) or a shortcut (Windows) to the file with the specified aliasName name in the folder designated by the destinationFolder object.

Pass the name of the alias or shortcut to create in the aliasName parameter.

By default on macOS, the function creates a standard alias. You can also create a symbolic link by using the aliasType parameter. The following constants are available:

ConstantValueComment
fk alias link0Alias link (default)
fk symbolic link1Symbolic link (macOS only)

On Windows, a shortcut (.lnk file) is always created (the aliasType parameter is ignored).

Returned object

A 4D.File object with the isAlias property set to true.

Example

You want to create an alias to a file in your database folder:

 $myFile:=Folder(fk documents folder).file("Archives/ReadMe.txt")
$aliasFile:=$myFile.createAlias(File("/PACKAGE");"ReadMe")

.delete()

History
ReleaseChanges
17 R5Added

.delete*()

ParameterTypeDescription
Does not require any parameters

Description

The .delete() function deletes the file.

If the file does not exist on disk, the function does nothing (no error is generated).

If the file is currently open, the result depends on the OS:

  • on Windows, an error is generated,
  • on macOS, no error is generated and the file is deleted.
caution

.delete() can delete any file on a disk. This includes documents created with other applications, as well as the applications themselves. .delete() should be used with extreme caution. Deleting a file is a permanent operation and cannot be undone.

Example

You want to delete a specific file in the database folder:

 $tempo:=File("/PACKAGE/SpecialPrefs/"+Current user+".prefs")
If($tempo.exists)
$tempo.delete()
ALERT("User preference file deleted.")
End if

.getAppInfo()

History
ReleaseChanges
20 R9Read UUIDs in macOS executables
19Added

.getAppInfo*() : Object

ParameterTypeDescription
ResultObject<-Application file information

Description

The .getAppInfo() function returns the contents of an application file information as an object.

The function must be used with an existing, supported file: .plist (all platforms), .exe/.dll (Windows), or macOS executable. If the file does not exist on disk or is not a supported file, the function returns an empty object (no error is generated).

Returned object with a .plist file (all platforms)

The xml file contents is parsed and keys are returned as properties of the object, preserving their types (text, boolean, number). .plist dict is returned as a JSON object and .plist array is returned as a JSON array.

note

The function only supports .plist files in xml format (text-based). An error is returned if it is used with a .plist file in binary format.

Returned object with a .exe or .dll file (Windows only)

All property values are Text.

PropertyType
InternalNameText
ProductNameText
CompanyNameText
LegalCopyrightText
ProductVersionText
FileDescriptionText
FileVersionText
OriginalFilenameText

Returned object with a macOS executable file (macOS only)

note

A macOS executable file is located within a package (e.g. myApp.app/Contents/MacOS/myApp).

The function returns an archs object that contains a collection of objects describing every architecture found in the executable (a fat executable can embed several architectures). Every object of the collection contains the following properties:

PropertyTypeDescription
nameTextName of architecture ("arm64" or "x86_64")
typeNumberNumerical identifier of the architecture
uuidTextTextual representation of the executable uuid

Example 1

  // display copyright info of an info.plist (any platform)
var $infoPlistFile : 4D.File
var $info : Object
$infoPlistFile:=File("/RESOURCES/info.plist")
$info:=$infoPlistFile.getAppInfo()
ALERT($info.Copyright)

Example 2

 // display copyright info of application .exe file (windows)
var $exeFile : 4D.File
var $info : Object
$exeFile:=File(Application file; fk platform path)
$info:=$exeFile.getAppInfo()
ALERT($info.LegalCopyright)

Example 3

 // Get uuids of an application (macOS)
var $app:=File("/Applications/myApp.app/Contents/MacOS/myApp")
var $info:=$app.getAppInfo()

Result in $info:

{
"archs":
[
{
"name":"x86_64",
"type":16777223,
"uuid":"3840983CDA32392DA4D1D32F08AB3212"
},
{
"name":"arm64",
"type":16777228,
"uuid":"E49F6BA275B931DDA183C0B0CDF0ADAF"
}
]
}

See also

.setAppInfo()

.moveTo()

History
ReleaseChanges
17 R5Added

.moveTo*( destinationFolder : 4D.Folder { ; newName : Text } ) : 4D.File

ParameterTypeDescription
destinationFolder4D.Folder->Destination folder
newNameText->Full name for the moved file
Result4D.File<-Moved file

Description

The .moveTo() function moves or renames the File object into the specified destinationFolder.

The destinationFolder must exist on disk, otherwise an error is generated.

By default, the file retains its name when moved. If you want to rename the moved file, pass the new full name in the newName parameter. The new name must comply with naming rules (e.g., it must not contain characters such as ":", "/", etc.), otherwise an error is returned.

Returned object

The moved File object.

Example

$DocFolder:=Folder(fk documents folder)
$myFile:=$DocFolder.file("Current/Infos.txt")
$myFile.moveTo($DocFolder.folder("Archives");"Infos_old.txt")

.open()

History
ReleaseChanges
19 R7Added

.open*( { mode : Text } ) : 4D.FileHandle
.open( { options : Object } ) : 4D.FileHandle

ParameterTypeDescription
modeText->Opening mode: "read", "write", "append"
optionsObject->Opening options
Result4D.FileHandle<-New File handle object

Description

The .open() function creates and returns a new 4D.FileHandle object on the file, in the specified mode or with the specified options. You can use functions and properties of the 4D.FileHandle class to write, read, or append contents to the file.

If you use the mode (text) parameter, pass the opening mode for the file handle:

modeDescription
"read"(Default) Creates a file handle to read values from the file. If the file does not exist on disk, an error is returned. You can open as many file handles as you want in "read" mode on the same File object.
"write"Creates a file handle to write values to the file (starting at the beginning of the file content). If the file does not exist on disk, it is created. You can open only one file handle in "write" mode on the same File object.
"append"Creates a file handle to write values to the file (starting at the end of the file content). If the file does not exist on disk, it is created. You can open only one file handle in "append" mode on the same File object.

The mode value is case sensitive.

If you use the options (object) parameter, you can pass more options for the file handle through the following properties (these properties can be read afterwards from the opened file handle object):

optionsTypeDescriptionDefault
.modeTextOpening mode (see mode above)"read"
.charsetTextCharset used when reading from or writing to the file. Use the standard name of the set (for example "ISO-8859-1" or "UTF-8")"UTF-8"
.breakModeReadText or NumberProcessing mode for line breaks used when reading in the file (see below)"native" or 1
.breakModeWriteText or NumberProcessing mode for line breaks used when writing to the file (see below)"native" or 1

The function replaces all original end-of-line delimiters. By default, the native delimiter is used, but you can define another delimiter. The .breakModeRead and .breakModeWrite indicate the processing to apply to end-of-line characters in the document. You can use one of the following values (text or number):

Break mode as textBreak mode as number (constant)Description
"native"1 (Document with native format)(Default) Line breaks are converted to the native format of the operating system: LF (line feed) under macOS, CRLF (carriage return + line feed) under Windows
"crlf"2 (Document with CRLF)Line breaks are converted to CRLF (carriage return + line feed), the default Windows format
"cr"3 (Document with CR)Line breaks are converted to CR (carriage return), the default Classic Mac OS format
"lf"4 (Document with LF)Line breaks are converted to LF (line feed), the default Unix and macOS format

The break mode as text value is case sensitive.

Example

You want to create a file handle for reading the "ReadMe.txt" file:

var $f : 4D.File
var $fhandle : 4D.FileHandle

$f:=File("C:\\Documents\\Archives\\ReadMe.txt";fk platform path)
$fhandle:=$f.open("read")

.rename()

History
ReleaseChanges
17 R5Added

.rename*( newName : Text ) : 4D.File

ParameterTypeDescription
newNameText->New full name for the file
Result4D.File<-Renamed file

Description

The .rename() function renames the file with the name you passed in newName and returns the renamed File object.

The newName parameter must comply with naming rules (e.g., it must not contain characters such as ":", "/", etc.), otherwise an error is returned. If a file with the same name already exists, an error is returned.

Note that the function modifies the full name of the file, i.e. if you do not pass an extension in newName, the file will have a name without an extension.

Returned object

The renamed File object.

Example

You want to rename "ReadMe.txt" in "ReadMe_new.txt":

 $toRename:=File("C:\\Documents\\Archives\\ReadMe.txt";fk platform path)
$newName:=$toRename.rename($toRename.name+"_new"+$toRename.extension)

.setAppInfo()

History
ReleaseChanges
20 R9Read UUIDs in macOS executables
20Support of WinIcon
19Added

.setAppInfo*( info : Object )

ParameterTypeDescription
infoObject->Properties to write in an application file information

Description

The .setAppInfo() function writes the info properties as information contents of an application file.

The function can only be used with the following file types: .plist (all platforms), existing .exe/.dll (Windows), or macOS executable. If used with another file type or with a .exe/.dll file that does not already exist on disk, the function does nothing (no error is generated).

info parameter object with a .plist file (all platforms)

note

The function only supports .plist files in xml format (text-based). An error is returned if it is used with a .plist file in binary format.

If the .plist file already exists on the disk, it is updated. Otherwise, it is created.

Each valid property set in the info object parameter is written in the .plist file as a key. Any key name is accepted. Value types are preserved when possible.

If a key set in the info parameter is already defined in the .plist file, its value is updated while keeping its original type. Other existing keys in the .plist file are left untouched.

note

To define a Date type value, the format to use is a json timestamp string formated in ISO UTC without milliseconds ("2003-02-01T01:02:03Z") like in the Xcode plist editor.

info parameter object with a .exe or .dll file (Windows only)

Each valid property set in the info object parameter is written in the version resource of the .exe or .dll file. Available properties are (any other property will be ignored):

PropertyTypeComment
InternalNameText
ProductNameText
CompanyNameText
LegalCopyrightText
ProductVersionText
FileDescriptionText
FileVersionText
OriginalFilenameText
WinIconTextPosix path of .ico file. This property applies only to 4D generated executable files.

For all properties except WinIcon, if you pass a null or empty text as value, an empty string is written in the property. If you pass a value type different from text, it is stringified.

For the WinIcon property, if the icon file does not exist or has an incorrect format, an error is generated.

info parameter object with a macOS executable file (macOS only)

info must be an object with a single property named archs that is a collection of objects in the format returned by getAppInfo(). Each object must contain at least the type and uuid properties (name is not used).

Every object in the info.archs collection must contain the following properties:

PropertyTypeDescription
typeNumberNumerical identifier of the architecture to modify
uuidTextTextual representation of the new executable uuid

Example 1

  // set some keys in an info.plist file (all platforms)
var $infoPlistFile : 4D.File
var $info : Object
$infoPlistFile:=File("/RESOURCES/info.plist")
$info:=New object
$info.Copyright:="Copyright 4D 2023" //text
$info.ProductVersion:=12 //integer
$info.ShipmentDate:="2023-04-22T06:00:00Z" //timestamp
$info.CFBundleIconFile:="myApp.icns" //for macOS
$infoPlistFile.setAppInfo($info)

Example 2

  // set copyright, version and icon of a .exe file (Windows)
var $exeFile; $iconFile : 4D.File
var $info : Object
$exeFile:=File(Application file; fk platform path)
$iconFile:=File("/RESOURCES/myApp.ico")
$info:=New object
$info.LegalCopyright:="Copyright 4D 2023"
$info.ProductVersion:="1.0.0"
$info.WinIcon:=$iconFile.path
$exeFile.setAppInfo($info)

Example 3

// regenerate uuids of an application (macOS)

// read myApp uuids
var $app:=File("/Applications/myApp.app/Contents/MacOS/myApp")
var $info:=$app.getAppInfo()

// regenerate uuids for all architectures
For each ($i; $info.archs)
$i.uuid:=Generate UUID
End for each

// update the app with the new uuids
$app.setAppInfo($info)

See also

.getAppInfo()

.setContent()

History
ReleaseChanges
17 R5Added

.setContent* ( content : Blob )

ParameterTypeDescription
contentBLOB->New contents for the file

Description

The .setContent( ) function rewrites the entire content of the file using the data stored in the content BLOB. For information on BLOBs, please refer to the BLOB section.

Example

 $myFile:=Folder(fk documents folder).file("Archives/data.txt")
$myFile.setContent([aTable]aBlobField)

.setText()

History
ReleaseChanges
19 R3Default for new projects: no BOM and (macOS) LF for EOL
17 R5Added

.setText* ( text : Text {; charSetName : Text { ; breakMode : Integer } } )
.setText ( text : Text {; charSetNum : Integer { ; breakMode : Integer } } )

ParameterTypeDescription
textText->Text to store in the file
charSetNameText->Name of character set
charSetNumInteger->Number of character set
breakModeInteger->Processing mode for line breaks

Description

The .setText() function writes text as the new contents of the file.

If the file referenced in the File object does not exist on the disk, it is created by the function. When the file already exists on the disk, its prior contents are erased, except if it is already open, in which case, its contents are locked and an error is generated.

In text, pass the text to write to the file. It can be a literal ("my text"), or a 4D text field or variable.

Optionally, you can designate the character set to be used for writing the contents. You can pass either:

  • in charSetName, a string containing the standard set name (for example "ISO-8859-1" or "UTF-8"),
  • or in charSetNum, the MIBEnum ID (number) of the standard set name.

For the list of character sets supported by 4D, refer to the description of the CONVERT FROM TEXT command.

If a Byte Order Mark (BOM) exists for the character set, 4D inserts it into the file unless the character set used contains the suffix "-no-bom" (e.g. "UTF-8-no-bom"). If you do not specify a character set, by default 4D uses the "UTF-8" character set without BOM.

In breakMode, you can pass a number indicating the processing to apply to end-of-line characters before saving them in the file. The following constants, found in the System Documents theme, are available:

ConstantValueComment
Document unchanged0No processing
Document with native format1(Default) Line breaks are converted to the native format of the operating system: LF (line feed) on macOS, CRLF (carriage return + line feed) on Windows
Document with CRLF2Line breaks are converted to CRLF (carriage return + line feed), the default Windows format
Document with CR3Line breaks are converted to CR (carriage return), the default Classic Mac OS format
Document with LF4Line breaks are converted to LF (line feed), the default Unix and macOS format

By default, when you omit the breakMode parameter, line breaks are processed in native mode (1).

Compatibility Note: Compatibility options are available for EOL and BOM management. See Compatibility page on doc.4d.com.

Example

$myFile:=File("C:\\Documents\\Hello.txt";fk platform path)
$myFile.setText("Hello world")