Skip to main content

%Library.File

stream class %Library.File extends %Library.AbstractStream

For information on this class, see Using %Library.File.

The %File class represents a disk file. It contains a number of class methods that provide a number of file system services.

For example,

  If ##class(%File).Exists("file.txt") Write "It exists",!
  

You can also create an instance of a %File object that represents a particular file. %File makes a number of file attributes accessible as properties as well as providing a %AbstractStream interface on the file.

For example,

  Set file=##class(%File).%New("file.txt")
  Write file.Size
  Do file.Open("WSN")
  Do file.WriteLine("This is a line of text")
  
Note that this class is a fairly simple wrapper around the ObjectScript file commands. For simply reading/writing to a file it is suggested that you look at the %Stream.FileCharacter and %Stream.FileBinary classes. These open the file using the correct mode automatically in order to read or write to the file and so are simpler to use.

Property Inventory

Method Inventory

Properties

property CanonicalName as %String (MAXLEN = 5000) [ Calculated ];
Read only property that returns the canonical filename if the file is open and "" if the file is not open.
Property methods: CanonicalNameDisplayToLogical(), CanonicalNameIsValid(), CanonicalNameLogicalToDisplay(), CanonicalNameLogicalToOdbc(), CanonicalNameNormalize()
property DateCreated as %Date [ Calculated ];
The creation date for this file (rounded to the millisecond). Only Windows maintains the created date; other operating systems return the date of the last file "status" change.
Property methods: DateCreatedDisplayToLogical(), DateCreatedIsValid(), DateCreatedLogicalToDisplay(), DateCreatedLogicalToOdbc(), DateCreatedNormalize(), DateCreatedOdbcToLogical()
property DateModified as %Date [ Calculated ];
The last modified date for this file (rounded to the millisecond).
Property methods: DateModifiedDisplayToLogical(), DateModifiedIsValid(), DateModifiedLogicalToDisplay(), DateModifiedLogicalToOdbc(), DateModifiedNormalize(), DateModifiedOdbcToLogical()
property IsOpen as %Boolean [ InitialExpression = 0 ];
True (1) if this file is currently open, false (0) otherwise.
Property methods: IsOpenDisplayToLogical(), IsOpenGet(), IsOpenIsValid(), IsOpenLogicalToDisplay(), IsOpenNormalize()
property Name as %String (MAXLEN = 5000);
The name of this file.
Property methods: NameDisplayToLogical(), NameGet(), NameIsValid(), NameLogicalToDisplay(), NameLogicalToOdbc(), NameNormalize(), NameSet()

Methods

classmethod Attributes(filename As %String) as %String
Return the attributes of the file. The format of the returned value depends on the underlying operating system.

Microsoft Windows® returns a value as a combination of bits whose meaning is:

  • 1: 0x00001 - Read-only
  • 2: 0x00002 - Hidden
  • 4: 0x00004 - System
  • 8: 0x00008 - Unused
  • 16: 0x00010 - Directory
  • 32: 0x00020 - Archive
  • 64: 0x00040 - Device
  • 128: 0x00080 - Normal
  • 256: 0x00100 - Temporary
  • 512: 0x00200- Sparse File
  • 1024: 0x00400 - Reparse Point
  • 2048: 0x00800 - Compressed
  • 4096: 0x01000 - Offline
  • 8192: 0x02000 - Content Not Indexed
  • 16384: 0x04000 - Encrypted
  • 32768: 0x08000 - Unused
  • 65536: 0x10000 - Virtual

In UNIX®, the returned value represents the mode map:

  • 1: 0x0001 - execute permission for others
  • 2: 0x0002 - write permission for others
  • 4: 0x0004 - read permission for others
  • 7: 0x0007 - mask for others permissions
  • 8: 0x0008 - execute permission for group
  • 16: 0x0010 - write permission for group
  • 32: 0x0020 - read permission for group
  • 56: 0x0038 - mask for group permissions
  • 64: 0x0040 - execute permission for owner
  • 128: 0x0080 - write permission for owner
  • 256: 0x0100 - read permission for owner
  • 448: 0x01C0 - mask for file owner permissions
  • 512: 0x0200 - sticky bit
  • 1024: 0x0400 - set groupid
  • 2048: 0x0800 - set userid
  • 4096: 0x1000 - fifo
  • 8192: 0x2000 - character device
  • 16384: 0x4000 - directory
  • 24576: 0x6000 - block device
  • 32768: 0x8000 - regular file
  • 40960: 0xA000 - symbolic link
  • 49152: 0xC000 - socket
  • 61440: 0xF000 - mask for file type

Note: Individual Operating System vendor differences may exist. The relevant man/help pages or other associated documentation should be consulted for a definitive description of the file attributes on a given system.

classmethod CanonicalFilename(filename As %String) as %String
Returns the canonical form of the filename. If the file can not be opened then it will return ""
method CanonicalNameGet() as %String
method Clear() as %Status
Inherited description: Clear the contents of this Stream from permanent storage. This will remove the permanent stream storage and any temporary stream and initialise the stream to its initial state that it starts in, including removing all the stream attributes.

Returns a %Status value indicating success or failure.

method Close()
Close the current file.
classmethod Compare(file1 As %String, file2 As %String) as %Boolean
Compare two files and return 1 if they are identical and 0 otherwise
classmethod ComplexDelete(filename As %String, Output return As %Integer) as %Integer
Handle delete of cases where filename contains a wildcard. Note: this does not delete subdirectories in the given directory; only files are removed. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
classmethod ComputeFullDBDir(filename As %String) as %String
Return the canonical form of the directory name filename. When filename is a non-full path directory, it will prefix the filename with Manager Path instead of current directory.
classmethod Construct(dirs... As %String) as %String
Pass in an array of paths you want to turn into a filename for the server platform, for example:
Set dirs($i(dirs))=$system.Util.DataDirectory()
  Set dirs($i(dirs))="httpd"
  Set dirs($i(dirs))="logs"
  Set filename=##class(%File).Construct(dirs...)
If you want the name returned to be a directory terminated with a '/' or '\' then pass in a null dirs entry as the last piece. You can also call Deconstruct() with the returned filename to turn this back into an array like dirs. If you pass in a blank array it will return the default directory.
classmethod CopyDir(pSource As %String, pTarget As %String, pOverlay As %Boolean = 0, ByRef pCreated=0, pDeleteBeforeCopy As %Boolean = 0) as %Boolean
Copy a host directory from pSource to pTarget.
Parameter pOverlay Parameter pDeleteBeforeCopy may be used to specify that any file that already exists in the target directory should be deleted before being overwritten with the source file. The default is 0 or false.
This method returns true if it succeeds and false otherwise.
Note: (1) If the target directory exists and pOverlay is false (default), then the operation fails. Also, if any of the target files exist and pDeleteBeforeCopy is false (default), then the operation may fail usually due to operating system characteristics. (2) The total number of files or directories created/copied during the operation can be gotten by passing a byref value in pCreated.
classmethod CopyFile(from As %String, to As %String, pDeleteBeforeCopy As %Boolean = 0, Output return As %Integer) as %Boolean
Copy a host file from to host file to.
Parameter pDeleteBeforeCopy may be used to specify that if the target file already exists then it should be deleted before being overwritten with the source file. The default is 0 or false.
This method returns true if it succeeds and false otherwise. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
method CopyFromAndSave(source As %AbstractStream) as %Status
Method not implemented as it does not make sense in context of %File interface
classmethod CreateDirectory(name As %String, Output return As %Integer) as %Boolean
Creates a directory with name name. Returns true if it succeeds and false otherwise. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
classmethod CreateDirectoryChain(name As %String, Output return As %Integer) as %Boolean
Create this directory and all the parent directories if they do not exist. This differs from CreateDirectory() as that method only creates one new directory where as this will create the entire chain of directories. Returns true if it succeeds and false otherwise. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
classmethod CreateNewDir(directory As %String, name As %String, Output return As %Integer) as %Boolean
Given a directory name and the name of a new directory create this directory inside the given directory. Return true if it succeeds and false otherwise. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
method DateCreatedGet() as %Date
method DateModifiedGet() as %Date
classmethod Deconstruct(filename As %String, ByRef dirs As %String)
Pass in a full valid filename for the server platform and it will decompose it into the dirs array with each integer subscript being a part of the path, this array can then be passed into Construct() to reconstruct the filename again. So on a Unix server you need to pass this a valid Unix filename and on a Windows server this should be passed a Windows filename.
classmethod Delete(filename As %String, Output return As %Integer) as %Integer
Deletes the file filename. Returns true if it succeeds and false otherwise. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
classmethod DirectoryExists(filename As %String) as %Boolean
Tests if filename is a directory. returns 1 if it is a directory, otherwise, returns 0.
classmethod DriveListClose(QHandle As %Binary) as %Status
classmethod DriveListExecute(ByRef QHandle As %Binary, fullyqualified As %Boolean = 0) as %Status
classmethod DriveListFetch(ByRef QHandle As %Binary, ByRef Row As %List, ByRef AtEnd As %Integer = 0) as %Status
classmethod Exists(filename As %String, Output return As %Integer) as %Boolean
Returns true (1) if filename exists. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
classmethod FileSetClose(QHandle As %Binary) as %Status
classmethod FileSetExecute(ByRef QHandle As %Binary, directory As %String, wildcards As %String, sortby As %String = "", includedirs As %Boolean = 0, delimiter As %String = ";") as %Status
classmethod FileSetFetch(ByRef QHandle As %Binary, ByRef Row As %List, ByRef AtEnd As %Integer = 0) as %Status
classmethod GetDirectory(name As %String, keepterm As %Boolean = 0) as %String
Given a full directory and filename this will return just the directory portion of this name. This is useful as the parsing of filenames on Unix/Windows is different.
classmethod GetDirectoryLength(name As %String) as %Integer
Return the number of pieces in this directory name
classmethod GetDirectoryPiece(name As %String, piece As %Integer, ByRef fullpath As %String, ByRef IsDrive As %Boolean) as %String
Return the piece of a directory name
classmethod GetDirectorySpace(Name As %String, ByRef FreeSpace As %String, ByRef TotalSpace As %String, Flag As %Integer = 1) as %Status
Return the amount of total space and free space in either Bytes,MB,GB on a drive or directory
Name = Valid Drive or directory specification
Flag = 0 - Return bytes
Flag = 1 - Return MB (Default)
Flag = 2 - Return GB

MB and GB returned are rounded to 2 decimal places.
Any error status returned is O/S level error. Note that on Windows only drives have a measurement for free space and directories can not so the FreeSpace is only returned for drives.
classmethod GetFileDateCreated(filename As %String, utc As %Boolean = 0) as %String
Return the date created of file filename in $H format, if the operating system supports it. Windows is the only current platform that tracks the created date. Other systems return the date of the last file "status" change. By default this is local time. If you pass utc as true it returns it in UTC time. The value is rounded to millisecond precision.
classmethod GetFileDateModified(filename As %String, utc As %Boolean = 0) as %String
Return the date last modified of file filename in $H format. By default this is local time. If you pass utc as true it returns it in UTC time. The value is rounded to millisecond precision.
classmethod GetFileSHA256Hash(filename As %String, ByRef sc=0) as %String
Return the SHA 256 hash of file filename.
classmethod GetFileSize(filename As %String) as %Integer
Return the size of file filename in bytes.
classmethod GetFilename(name As %String) as %String
Given a full directory and filename this will return just the filename portion of this name. This is useful as the parsing of filenames on Unix/Windows is different.
classmethod GetOwnerGroup(File As %String, ByRef OwnerGroup As %String) as %Status
Return the Owner and Group of a file or directory in the format Owner:Group.
method LastModifiedGet() as %TimeStamp
classmethod ManagerDirectory() as %String
Returns the path of the manager directory.
classmethod NormalizeDirectory(directory As %String, absolutedirectory As %String = "", addnull As %Boolean) as %String
Returns a normalized absolute directory from the directory that is passed in including any trailing directory delimiter.

If the directory is a relative path (rather than an absolute path) then the absolutedirectory parameter determines what we normalize the directory compoent relative to. If absolutedirectory is "" or not passed in then we normalize relative to the current default directory otherwise we will normalize relative to the passed in absolutedirectory.

addnull use is deprecated

classmethod NormalizeFilename(filename As %String, directory As %String = "") as %String
Returns the normalized form of the filename. If you pass directory then it will normalize this filename relative to the provided directory, if no directory is supplied then it is relative to the current default directory. If the directory does not exist then this method will return the empty string. Otherwise, this method returns the normalized full path name of the specified file.
classmethod NormalizeFilenameWithSpaces(pathname As %String) as %String
Normalize filenames containing spaces for the host platform.

Parameter
pathname : A filename or pathname.

Description
The NormalizeFilenameWithSpaces class method handles spaces in pathnames as appropriate to the host platform.

If a pathname contains spaces NormalizeFilenameWithSpaces returns the pathname enclosed in double quotes ("path name"). If a pathname does not contain spaces, the method returns it unchanged. NormalizeFilenameWithSpaces performs no other pathname validation.

NormalizefilenameWithSpaces is commonly used with the $ZF() functions.

Note that this method does not perform the normalization actions of NormalizeFilename().
method Open(mode As %String = "", timeout As %Integer = 0) as %Status
Open the current file with mode mode.

mode is a string containing one or more file modes including:

RRead
WWrite
SStream mode
NCreate a new file (overwrite existing file)
Note that if the mode contains ':' characters this is a delimiter. For example if the mode="RN:/SHARED" then it will open the file with the equivalent of the COS command 'Open name:("RN":/SHARED):0'. The first piece before the ':' is quoted and the subsequent pieces are not.

A complete discussion of the available options for mode can be found in the online documentation in the book, I/O Devices Guide, specifically the chapter on Sequential File I/O.

classmethod ParentDirectoryName(directory As %String) as %String
Given a directory name, return the name of its parent directory.
If the directory is already the root (e.g., "/" on Unix, "c:\" on Windows), return the root.
classmethod ParseDirectoryClose(ByRef QHandle As %Binary) as %Status
classmethod ParseDirectoryExecute(ByRef QHandle As %Binary, directory As %String) as %Status
classmethod ParseDirectoryFetch(ByRef QHandle As %Binary, ByRef Row As %List, ByRef AtEnd As %Integer = 0) as %Status
method Read(ByRef len As %Integer = 32000, ByRef sc As %Status) as %RawString
Read up to len characters from this File.
classmethod ReadOnly(filename As %String) as %Integer
Return true if the file is read only and false if it is writable
classmethod RemoveDirectory(name As %String, Output return As %Integer) as %Integer
Removes directory name. Returns true if it succeeds and false otherwise. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
classmethod RemoveDirectoryTree(pTarget As %String) as %Integer
Recursively remove directory pTarget. Returns true if it succeeds and false otherwise.
classmethod Rename(oldname As %String, newname As %String, Output return As %Integer) as %Integer
Rename file oldname to newname. Returns true if it succeeds and false otherwise. The rename subfunction is only intended for changing the name of a regular file, not directories or other types of files. In particular, renaming a file across filesystems results in copying and deleting the original file, but this will not work for a directory. Renaming a directory within a file system does work. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
method Rewind() as %Status
Moves the current location to the beginning of the stream.
classmethod SHA1Hash(file As %String, type As %Integer = 0) as %String
Return binary form of SHA1 hash on the file if type is 0 (the default). If you want the string version then pass in type as 1. Note that if you already have the file open in this process calling this function will close this file.
classmethod SetAttributes(filename As %String, attributes As %String, Output return As %Integer) as %Boolean
Set the OS specific attributes of the file. See the Attribute method in this class for file attribute values. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
method SetFileDateModified(filename As %String, ntime As %TimeStamp, utc As %Boolean = 0, Output return As %Integer) as %Status
Set the date last modified of file filename to be ntime in $H format. By default ntime is local time. If you pass utc as true, ntime will be treated as UTC time. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
classmethod SetOwnerGroup(filename, OwnerGroup) as %Status
Set the Owner and Group of a file or directory.
This uses the unix "chown" command to perform the operation, and is valid only on Unix platforms.
classmethod SetReadOnly(filename As %String, leaveexisting As %Boolean = 0, Output return As %Integer) as %Boolean
Make this file/directory read only (if we can). If leaveexisting is true then it will add read permissions to the file/directory without changing the existing permissions, by default it will remove all other permissions other than read only flags. The leaveexisting has no effect on Windows so you do not need to pass this argument on this platform. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
classmethod SetUMask(NewMask As %Integer) as %Integer
Set umask to the given value and return the previous umask value
classmethod SetWriteable(filename As %String, writeonly As %Boolean = 1, Output return As %Integer) as %Boolean
Make this file/directory writable (if we can). The writeonly defaults to true in which case this makes the file write only, if you just want to add writable to the existing permissions without modifying the other permissions pass writeonly=0. The writeonly has no effect on Windows so you do not need to pass this argument on this platform. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
method SizeGet() as %Integer
classmethod SubDirectoryName(directory As %String, name As %String, normalized As %Boolean = 0) as %String
Given a directory name and the name of a sub directory create the name for the subdirectory inside the given directory. Return the new directory name. This is useful as the parsing of filenames on Unix/Windows is different.
classmethod TempFilename(ext As %String, dir As %String, Output return As %Integer) as %String
Return a temporary filename in the OS provided temp directory or the directory specified by dir.
If you specify ext the temp filename will have this extension.
Pass return by reference to obtain the low level return value in case of an error. It will be the negative value of the operating system return code, or 0 if there is no error.
In case of an error, the method returns an empty string.
classmethod Truncate(filename As %String, Output return As %Integer) as %Boolean
Truncate an existing file or create a new empty file. Pass return by reference to obtain the low level return value in case of errors which is the negative value of the operating system return code.
method Write(data As %RawString = "") as %Status
Write data to this %File object.
method WriteLine(data As %RawString = "") as %Status
Write data with a carriage return to this %File object.
classmethod Writeable(filename As %String) as %Boolean
Return true if the file/directory is writable and false if it is not

Queries

query DriveList(fullyqualified As %Boolean = 0)
Selects Drive As %String
This query was originally created to return Windows drive letters, hence its name. Later it was extended to work on Unix.
  • Windows: return a list of available drives
  • Unix: return a list of mounted file systems
On Windows, if fullyqualified is true then the drive letters include the trailing '\' character. The default is false; this is backward compatible and returns 'c:' on Windows. This does not affect the behavior on Unix.
query FileSet(directory As %String(MAXLEN=""), wildcards As %String, sortby As %String = "", includedirs As %Boolean = 0, delimiter As %String = ";")
Selects Name As %String, Type As %String, Size As %BigInt, DateCreated As %TimeStamp, DateModified As %TimeStamp, ItemName As %String
Return the list of files in directory matching the pattern wildcards. The sortby can be one of:
  • Name - the name of the file (the default)
  • Type - file type
  • DateCreated - the date the file was created (rounded to the millisecond)
  • DateModified - the date the file was last modified (rounded to the millisecond)
  • Size - the file size
The includedirs if true (default is 0) will force the list of all directories to be returned before any files, the directories will ignore the pattern you supplied so it returns them all. If it is false it will return any files that match the pattern you give it, this may include directories if they match the pattern as well. So true forces any directory to be included, but false does not exclude directories. You may also specify the delimiter that is used to separate the wildcards from each other, this defaults to ";".
query ParseDirectory(directory As %String(MAXLEN=""))
Selects Name As %String, IsDrive As %Boolean, Directory As %String
Given a directory name return it pulled apart into individual subdirectories starting at the root node and working down to the last directory name

Inherited Members

Inherited Properties

Inherited Methods

FeedbackOpens in a new tab