Class FileAccess
- Namespace
- Godot
- Assembly
- GodotSharp.dll
This class can be used to permanently store data in the user device's file system and to read from it. This is useful for store game save data or player configuration files.
Here's a sample on how to write and read from a file:
public void Save(string content)
{
using var file = FileAccess.Open("user://save_game.dat", FileAccess.ModeFlags.Write);
file.StoreString(content);
}
public string Load()
{
using var file = FileAccess.Open("user://save_game.dat", FileAccess.ModeFlags.Read);
string content = file.GetAsText();
return content;
}
In the example above, the file will be saved in the user data folder as specified in the Data paths documentation.
FileAccess will close when it's freed, which happens when it goes out of scope or when it gets assigned with null
. Close() can be used to close it before then explicitly. In C# the reference must be disposed manually, which can be done with the using
statement or by calling the Dispose
method directly.
Note: To access project resources once exported, it is recommended to use ResourceLoader instead of FileAccess, as some files are converted to engine-specific formats and their original source files might not be present in the exported PCK package.
Note: Files are automatically closed only if the process exits "normally" (such as by clicking the window manager's close button or pressing Alt + F4). If you stop the project execution by pressing F8 while the project is running, the file won't be closed as the game process will be killed. You can work around this by calling Flush() at regular intervals.
public class FileAccess : RefCounted, IDisposable
- Inheritance
-
FileAccess
- Implements
- Inherited Members
Properties
BigEndian
If true
, the file is read with big-endian endianness. If false
, the file is read with little-endian endianness. If in doubt, leave this to false
as most files are written with little-endian endianness.
Note: BigEndian is only about the file format, not the CPU type. The CPU endianness doesn't affect the default endianness for files written.
Note: This is always reset to false
whenever you open the file. Therefore, you must set BigEndianafter opening the file, not before.
public bool BigEndian { get; set; }
Property Value
Methods
Close()
Closes the currently opened file and prevents subsequent read/write operations. Use Flush() to persist the data to disk without closing the file.
Note:
FileAccess will automatically close when it's freed, which happens when it goes out of scope or when it gets assigned with null
. In C# the reference must be disposed after we are done using it, this can be done with the using
statement or calling the Dispose
method directly.
public void Close()
EofReached()
Returns true
if the file cursor has already read past the end of the file.
Note:
eof_reached() == false
cannot be used to check whether there is more data available. To loop while there is more data available, use:
while (file.GetPosition() < file.GetLength())
{
// Read data
}
public bool EofReached()
Returns
FileExists(string)
Returns true
if the file exists in the given path.
Note: Many resources types are imported (e.g. textures or sound files), and their source asset will not be included in the exported game, as only the imported version is used. See Exists(string, string) for an alternative approach that takes resource remapping into account.
For a non-static, relative equivalent, use FileExists(string).
public static bool FileExists(string path)
Parameters
path
string
Returns
Flush()
Writes the file's buffer to disk. Flushing is automatically performed when the file is closed. This means you don't need to call Flush() manually before closing a file. Still, calling Flush() can be used to ensure the data is safe even if the project crashes instead of being closed gracefully.
Note: Only call Flush() when you actually need it. Otherwise, it will decrease performance due to constant disk writes.
public void Flush()
Get16()
Returns the next 16 bits from the file as an integer. See Store16(ushort) for details on what values can be stored and retrieved this way.
public ushort Get16()
Returns
Get32()
Returns the next 32 bits from the file as an integer. See Store32(uint) for details on what values can be stored and retrieved this way.
public uint Get32()
Returns
Get64()
Returns the next 64 bits from the file as an integer. See Store64(ulong) for details on what values can be stored and retrieved this way.
public ulong Get64()
Returns
Get8()
Returns the next 8 bits from the file as an integer. See Store8(byte) for details on what values can be stored and retrieved this way.
public byte Get8()
Returns
GetAsText(bool)
Returns the whole file as a string. Text is interpreted as being UTF-8 encoded.
If skipCr
is true
, carriage return characters (\r
, CR) will be ignored when parsing the UTF-8, so that only line feed characters (\n
, LF) represent a new line (Unix convention).
public string GetAsText(bool skipCr = false)
Parameters
skipCr
bool
Returns
GetBuffer(long)
Returns next length
bytes of the file as a byte[].
public byte[] GetBuffer(long length)
Parameters
length
long
Returns
- byte[]
GetCsvLine(string)
Returns the next value of the file in CSV (Comma-Separated Values) format. You can pass a different delimiter delim
to use other than the default ","
(comma). This delimiter must be one-character long, and cannot be a double quotation mark.
Text is interpreted as being UTF-8 encoded. Text values must be enclosed in double quotes if they include the delimiter character. Double quotes within a text value can be escaped by doubling their occurrence.
For example, the following CSV lines are valid and will be properly parsed as two strings each:
Alice,"Hello, Bob!"
Bob,Alice! What a surprise!
Alice,"I thought you'd reply with ""Hello, world""."
Note how the second line can omit the enclosing quotes as it does not include the delimiter. However it could very well use quotes, it was only written without for demonstration purposes. The third line must use ""
for each quotation mark that needs to be interpreted as such instead of the end of a text value.
public string[] GetCsvLine(string delim = ",")
Parameters
delim
string
Returns
- string[]
GetDouble()
Returns the next 64 bits from the file as a floating-point number.
public double GetDouble()
Returns
GetError()
Returns the last error that happened when trying to perform operations. Compare with the ERR_FILE_*
constants from Error.
public Error GetError()
Returns
GetFileAsBytes(string)
Returns the whole path
file contents as a byte[] without any decoding.
Returns an empty byte[] if an error occurred while opening the file. You can use GetOpenError() to check the error that occurred.
public static byte[] GetFileAsBytes(string path)
Parameters
path
string
Returns
- byte[]
GetFileAsString(string)
Returns the whole path
file contents as a string. Text is interpreted as being UTF-8 encoded.
Returns an empty string if an error occurred while opening the file. You can use GetOpenError() to check the error that occurred.
public static string GetFileAsString(string path)
Parameters
path
string
Returns
GetFloat()
Returns the next 32 bits from the file as a floating-point number.
public float GetFloat()
Returns
GetHiddenAttribute(string)
Returns true
, if file hidden
attribute is set.
Note: This method is implemented on iOS, BSD, macOS, and Windows.
public static bool GetHiddenAttribute(string file)
Parameters
file
string
Returns
GetLength()
Returns the size of the file in bytes.
public ulong GetLength()
Returns
GetLine()
Returns the next line of the file as a string.
Text is interpreted as being UTF-8 encoded.
public string GetLine()
Returns
GetMd5(string)
Returns an MD5 String representing the file at the given path or an empty string on failure.
public static string GetMd5(string path)
Parameters
path
string
Returns
GetModifiedTime(string)
Returns the last time the file
was modified in Unix timestamp format, or 0
on error. This Unix timestamp can be converted to another format using the Time singleton.
public static ulong GetModifiedTime(string file)
Parameters
file
string
Returns
GetOpenError()
Returns the result of the last Open(string, ModeFlags) call in the current thread.
public static Error GetOpenError()
Returns
GetPascalString()
Returns a string saved in Pascal format from the file.
Text is interpreted as being UTF-8 encoded.
public string GetPascalString()
Returns
GetPath()
Returns the path as a string for the current open file.
public string GetPath()
Returns
GetPathAbsolute()
Returns the absolute path as a string for the current open file.
public string GetPathAbsolute()
Returns
GetPosition()
Returns the file cursor's position.
public ulong GetPosition()
Returns
GetReadOnlyAttribute(string)
Returns true
, if file read only
attribute is set.
Note: This method is implemented on iOS, BSD, macOS, and Windows.
public static bool GetReadOnlyAttribute(string file)
Parameters
file
string
Returns
GetReal()
Returns the next bits from the file as a floating-point number.
public float GetReal()
Returns
GetSha256(string)
public static string GetSha256(string path)
Parameters
path
string
Returns
GetUnixPermissions(string)
Returns file UNIX permissions.
Note: This method is implemented on iOS, Linux/BSD, and macOS.
public static FileAccess.UnixPermissionFlags GetUnixPermissions(string file)
Parameters
file
string
Returns
GetVar(bool)
Returns the next Variant value from the file. If allowObjects
is true
, decoding objects is allowed.
Internally, this uses the same decoding mechanism as the @GlobalScope.bytes_to_var
method.
Warning: Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats such as remote code execution.
public Variant GetVar(bool allowObjects = false)
Parameters
allowObjects
bool
Returns
HasGodotClassMethod(in godot_string_name)
Check if the type contains a method with the given name. This method is used by Godot to check if a method exists before invoking it. Do not call or override this method.
protected override bool HasGodotClassMethod(in godot_string_name method)
Parameters
method
godot_string_nameName of the method to check for.
Returns
HasGodotClassSignal(in godot_string_name)
Check if the type contains a signal with the given name. This method is used by Godot to check if a signal exists before raising it. Do not call or override this method.
protected override bool HasGodotClassSignal(in godot_string_name signal)
Parameters
signal
godot_string_nameName of the signal to check for.
Returns
InvokeGodotClassMethod(in godot_string_name, NativeVariantPtrArgs, out godot_variant)
Invokes the method with the given name, using the given arguments. This method is used by Godot to invoke methods from the engine side. Do not call or override this method.
protected override bool InvokeGodotClassMethod(in godot_string_name method, NativeVariantPtrArgs args, out godot_variant ret)
Parameters
method
godot_string_nameName of the method to invoke.
args
NativeVariantPtrArgsArguments to use with the invoked method.
ret
godot_variantValue returned by the invoked method.
Returns
IsOpen()
Returns true
if the file is currently opened.
public bool IsOpen()
Returns
Open(string, ModeFlags)
Creates a new FileAccess object and opens the file for writing or reading, depending on the flags.
Returns null
if opening the file failed. You can use GetOpenError() to check the error that occurred.
public static FileAccess Open(string path, FileAccess.ModeFlags flags)
Parameters
path
stringflags
FileAccess.ModeFlags
Returns
OpenCompressed(string, ModeFlags, CompressionMode)
Creates a new FileAccess object and opens a compressed file for reading or writing.
Note: OpenCompressed(string, ModeFlags, CompressionMode) can only read files that were saved by Godot, not third-party compression formats. See GitHub issue #28999 for a workaround.
Returns null
if opening the file failed. You can use GetOpenError() to check the error that occurred.
public static FileAccess OpenCompressed(string path, FileAccess.ModeFlags modeFlags, FileAccess.CompressionMode compressionMode = CompressionMode.Fastlz)
Parameters
path
stringmodeFlags
FileAccess.ModeFlagscompressionMode
FileAccess.CompressionMode
Returns
OpenEncrypted(string, ModeFlags, byte[])
Creates a new FileAccess object and opens an encrypted file in write or read mode. You need to pass a binary key to encrypt/decrypt it.
Note: The provided key must be 32 bytes long.
Returns null
if opening the file failed. You can use GetOpenError() to check the error that occurred.
public static FileAccess OpenEncrypted(string path, FileAccess.ModeFlags modeFlags, byte[] key)
Parameters
path
stringmodeFlags
FileAccess.ModeFlagskey
byte[]
Returns
OpenEncryptedWithPass(string, ModeFlags, string)
Creates a new FileAccess object and opens an encrypted file in write or read mode. You need to pass a password to encrypt/decrypt it.
Returns null
if opening the file failed. You can use GetOpenError() to check the error that occurred.
public static FileAccess OpenEncryptedWithPass(string path, FileAccess.ModeFlags modeFlags, string pass)
Parameters
path
stringmodeFlags
FileAccess.ModeFlagspass
string
Returns
Seek(ulong)
Changes the file reading/writing cursor to the specified position (in bytes from the beginning of the file).
public void Seek(ulong position)
Parameters
position
ulong
SeekEnd(long)
Changes the file reading/writing cursor to the specified position (in bytes from the end of the file).
Note: This is an offset, so you should use negative numbers or the cursor will be at the end of the file.
public void SeekEnd(long position = 0)
Parameters
position
long
SetHiddenAttribute(string, bool)
Sets file hidden attribute.
Note: This method is implemented on iOS, BSD, macOS, and Windows.
public static Error SetHiddenAttribute(string file, bool hidden)
Parameters
Returns
SetReadOnlyAttribute(string, bool)
Sets file read only attribute.
Note: This method is implemented on iOS, BSD, macOS, and Windows.
public static Error SetReadOnlyAttribute(string file, bool ro)
Parameters
Returns
SetUnixPermissions(string, UnixPermissionFlags)
Sets file UNIX permissions.
Note: This method is implemented on iOS, Linux/BSD, and macOS.
public static Error SetUnixPermissions(string file, FileAccess.UnixPermissionFlags permissions)
Parameters
file
stringpermissions
FileAccess.UnixPermissionFlags
Returns
Store16(ushort)
Stores an integer as 16 bits in the file.
Note: The value
should lie in the interval [0, 2^16 - 1]
. Any other value will overflow and wrap around.
To store a signed integer, use Store64(ulong) or store a signed integer from the interval [-2^15, 2^15 - 1]
(i.e. keeping one bit for the signedness) and compute its sign manually when reading. For example:
public override void _Ready()
{
using var f = FileAccess.Open("user://file.dat", FileAccess.ModeFlags.WriteRead);
f.Store16(unchecked((ushort)-42)); // This wraps around and stores 65494 (2^16 - 42).
f.Store16(121); // In bounds, will store 121.
f.Seek(0); // Go back to start to read the stored value.
ushort read1 = f.Get16(); // 65494
ushort read2 = f.Get16(); // 121
short converted1 = (short)read1; // -42
short converted2 = (short)read2; // 121
}
public void Store16(ushort value)
Parameters
value
ushort
Store32(uint)
Stores an integer as 32 bits in the file.
Note: The value
should lie in the interval [0, 2^32 - 1]
. Any other value will overflow and wrap around.
To store a signed integer, use Store64(ulong), or convert it manually (see Store16(ushort) for an example).
public void Store32(uint value)
Parameters
value
uint
Store64(ulong)
Stores an integer as 64 bits in the file.
Note: The value
must lie in the interval [-2^63, 2^63 - 1]
(i.e. be a valid int value).
public void Store64(ulong value)
Parameters
value
ulong
Store8(byte)
Stores an integer as 8 bits in the file.
Note: The value
should lie in the interval [0, 255]
. Any other value will overflow and wrap around.
To store a signed integer, use Store64(ulong), or convert it manually (see Store16(ushort) for an example).
public void Store8(byte value)
Parameters
value
byte
StoreBuffer(byte[])
Stores the given array of bytes in the file.
public void StoreBuffer(byte[] buffer)
Parameters
buffer
byte[]
StoreCsvLine(string[], string)
Store the given string[] in the file as a line formatted in the CSV (Comma-Separated Values) format. You can pass a different delimiter delim
to use other than the default ","
(comma). This delimiter must be one-character long.
Text will be encoded as UTF-8.
public void StoreCsvLine(string[] values, string delim = ",")
Parameters
StoreDouble(double)
Stores a floating-point number as 64 bits in the file.
public void StoreDouble(double value)
Parameters
value
double
StoreFloat(float)
Stores a floating-point number as 32 bits in the file.
public void StoreFloat(float value)
Parameters
value
float
StoreLine(string)
Appends line
to the file followed by a line return character (\n
), encoding the text as UTF-8.
public void StoreLine(string line)
Parameters
line
string
StorePascalString(string)
Stores the given string as a line in the file in Pascal format (i.e. also store the length of the string).
Text will be encoded as UTF-8.
public void StorePascalString(string @string)
Parameters
string
string
StoreReal(float)
Stores a floating-point number in the file.
public void StoreReal(float value)
Parameters
value
float
StoreString(string)
Appends string
to the file without a line return, encoding the text as UTF-8.
Note: This method is intended to be used to write text files. The string is stored as a UTF-8 encoded buffer without string length or terminating zero, which means that it can't be loaded back easily. If you want to store a retrievable string in a binary file, consider using StorePascalString(string) instead. For retrieving strings from a text file, you can use get_buffer(length).get_string_from_utf8()
(if you know the length) or GetAsText(bool).
public void StoreString(string @string)
Parameters
string
string
StoreVar(Variant, bool)
Stores any Variant value in the file. If fullObjects
is true
, encoding objects is allowed (and can potentially include code).
Internally, this uses the same encoding mechanism as the @GlobalScope.var_to_bytes
method.
Note: Not all properties are included. Only properties that are configured with the Storage flag set will be serialized. You can add a new usage flag to a property by overriding the _GetPropertyList() method in your class. You can also check how property usage is configured by calling _GetPropertyList(). See PropertyUsageFlags for the possible usage flags.
public void StoreVar(Variant value, bool fullObjects = false)