Class FileSystem
Provides static methods and properties to access file system related functionality
public static class FileSystem
- Inheritance
-
FileSystem
- Inherited Members
Remarks
SDL offers an APIs for examining and manipulating the system's file system. This covers most things one would need to do with directories, except for actual file I/O (which is covered by File, Stream, AsyncIO, and partially by Storage instead).
There are the members to answer necessary path questions:
- Where is my app's data?BasePath
- Where can I safely write files?TryGetPreferencesPath(string?, string, out string?)
- Where are paths like Downloads, Desktop, Music?TryGetUserFolder(Folder, out string?)
- What is this thing at this location?TryGetPathInfo(string, out PathInfo)
- What items live in this folder?TryEnumerateDirectory(string, EnumerateDirectoryCallback) or EnumerateDirectory(string)
- What items live in this folder by wildcard?TryGlobDirectory(string, string?, GlobFlags, out string[]?)
- What is my current working directory?CurrentDirectory
SDL'S APIs also offers functionality to manipulate the directory tree: renaming, removing, copying files.
Properties
BasePath
Gets the path where the application was run from
public static string? BasePath { get; }
Property Value
- string
The path where the application was run from, or
nullon error or when the plaform does not support this functionality (check TryGet(out string?) for more information)
Remarks
While SDL caches the value of this property internally, the first access to this property is not necessarily fast, so plan accordingly.
- macOS and iOS Specific Functionality
If the application is in a ".app" bundle, the value of this property will be the resource directory (e.g.
"MyApp.app/Contents/Resources/"). This behaviour can be overridden by adding a property to the Info.plist file. Adding a string key with the nameSDL_FILESYSTEM_BASE_DIR_TYPEwith a supported value will change the behaviour.Supported values for the
SDL_FILESYSTEM_BASE_DIR_TYPEproperty are:<ul><li><span class="term"><code>resource</code></span>The bundle's resource directory. For example: <code>"/Applications/SDLApp/MyApp.app/"</code>. This is the default.</li><li><span class="term"><code>bundle</code></span>The bundle directory. For example: <code>"/Applications/SDLApp/MyApp.app/"</code>.</li><li><span class="term"><code>parent</code></span>The containing directory of the bundle. For example: <code>"/Applications/SDLApp/"</code>.</li></ul> </p> </li><li><span class="term">Nintendo 3DS Specific Functionality</span> <p> The value of this property will be "romfs" directory of the application, as it is uncommon to store resources outside the executable. As such it is not a writable directory. </p> </li></ul>The value of this property is guaranteed to end with a directory separator character (
'\\'on Windows;'/'on most other platforms).
CurrentDirectory
Gets what the system considers the "current working directory"
public static string? CurrentDirectory { get; }
Property Value
Remarks
For systems without a concept of a current working directory, this will still attempt to provide something reasonable.
SDL does not provide the means to change the current working directory (for platforms without this concept). Please use the provided .NET APIs to change the current working directory if needed.
The value of this property is guaranteed to end with a directory separator character ('\\' on Windows; '/' on most other platforms).
Methods
EnumerateDirectory(string)
Enumerates file system entries for a specified directory path
public static FileSystem.DirectoryEnumerable EnumerateDirectory(string path)
Parameters
pathstringThe path to the directory to enumerate
Returns
- FileSystem.DirectoryEnumerable
A FileSystem.DirectoryEnumerable that can be used to enumerate the file system entries for the specified directory
path
Exceptions
- ArgumentException
pathisnull, empty, or consists exclusively of white-space characters
PathExists(string)
Determines whether a file system entry exists at a specified path
public static bool PathExists(string path)
Parameters
pathstringThe path to the file system entry
Returns
TryCopyFile(string, string)
Tries to copy a file from one path to another
public static bool TryCopyFile(string oldPath, string newPath)
Parameters
Returns
- bool
true, if the file was copied successfully; otherwise,false(check TryGet(out string?) for more information)
Remarks
If the file at newPath already exists, it will be overwritten with the contents of the file at oldPath.
This method will block until the copy is complete, which might be a significant time for large files on slow disks. On some platforms, the copy can be handed off to the OS itself, but on others SDL might just open both paths, and read from one and write to the other.
Note: this is not an atomic operation! If something tries to read from newPath while the copy is in progress, it will see an incomplete copy of the data, and if the calling thread terminates (or the power goes out) during the copy, newPath's previous contents will be gone, replaced with an incomplete copy of the data.
To avoid this risk, it is recommended that you copy to a temporary file in the same directory as newPath first, and if the copy is successful, use TryRenamePath(string, string) to replace newPath with the temporary file.
This will ensure that reads of newPath will either see a complete copy of the data, or it will see the pre-copy state of the file at newPath.
This method attempts to synchronize the newly-copied data to disk before returning, if the platform allows it, so that the renaming trick will not have a problem in a system crash or power failure, where the file could be renamed but the contents never made it from the system file cache to the physical disk.
If the copy operation fails for any reason, the state of the file system entry at newPath is undefined.
It might be half a copy, it might be the untouched data of what was already there, or it might be a zero-byte file, etc.
While it's safe to call this method from any thread, the operation itself is not atomic, so you'll might need to protect access to specific paths from other threads if appropriate.
TryCreateDirectory(string)
Tries to create a directory, and any missing parent directories, at the specified path
public static bool TryCreateDirectory(string path)
Parameters
pathstringThe path to the directory to create
Returns
- bool
true, if the directory was created successfully; otherwise,false(check TryGet(out string?) for more information)
Remarks
This method returns true if the directory already exists.
If any parent directories in the specified path do not exist, they will be created as well. Please note, that if the operation fails at any point, parent directories that were already created will not be removed.
TryEnumerateDirectory(string, EnumerateDirectoryCallback)
Tries to enumerate file system entries in a directory
public static bool TryEnumerateDirectory(string path, EnumerateDirectoryCallback callback)
Parameters
pathstringThe path to the directory to enumerate
callbackEnumerateDirectoryCallbackThe callback to invoke for each file system entry
Returns
- bool
true, if the enumeration was successful; otherwise,false(check TryGet(out string?) for more information)
Remarks
This method will continue enumerating file system entries until all entries have been enumerated, or until the provided callback returns either Success or Failure.
This method will return false, if there was an error in general, or if the provided callback returned Failure.
A return value of true indicates that all file system entries were enumerated successfully, or that the provided callback returned Success.
Exceptions
- ArgumentNullException
callbackisnull
TryGetPathInfo(string, out PathInfo)
Tries to get information about a file system path
public static bool TryGetPathInfo(string path, out PathInfo info)
Parameters
Returns
- bool
true, if the information about the file system path was retrieved successfully; otherwise,false(check TryGet(out string?) for more information)
TryGetPreferencesPath(string?, string, out string?)
Tries to get the user-and-application-specific path where files can be written to
public static bool TryGetPreferencesPath(string? orgName, string appName, out string? preferencesPath)
Parameters
orgNamestringThe name of your organization
appNamestringThe name of your application
preferencesPathstringThe path to the preferences directory, when this method returns
true; otherwise,null
Returns
Remarks
The "preferences path" is a directory, that is meant to store the user's personal files (preferences and save games, etc) that are specific to your application. This directory is unique per user, per application.
This method will decide the appropriate location in the native filesystem, create the directory if necessary, and result in the absolute path to that directory.
Examples for "preferences paths" are:
- On Windows
"C:\\Users\\bob\\AppData\\Roaming\\My Company\\My Program Name\\" - On Linux
"/home/bob/.local/share/My Program Name/" - On macOS
"/Users/bob/Library/Application Support/My Program Name/"
You should assume that the resulting path of a call to this method is the only safe place to write files to (and that BasePath, while it might be writable, or even the parent of the resulting path, isn't where you should be writing things).
Both the orgName and appName may become part of a directory name, so please follow these rules:
-
Try to use the same value for
orgName(including case-sensitivity) for all your applications that use this functionality. -
Always use an unique value for
appNamefor each individual application, and make sure it never changes for an application once you've decided on it. - Unicode characters are legal, but you should only use letters, numbers, and spaces. Avoid punctuation like "Game Name 2: Bad Guy's Revenge!", "Game Name 2" is sufficient.
Due to historical mistakes, orgName is allowed to be null or the empty string ("").
In such cases, SDL will omit the subdirectory for orgName, including on platforms where it shouldn't, and including on platforms where this would make your app fail certification for an app store.
Newly created application should definitely specify a non-null, non-empty value for orgName!
The resulting preferencesPath is guaranteed to end with a directory separator character ('\\' on Windows; '/' on most other platforms).
TryGetUserFolder(Folder, out string?)
Tries to get the path to a most suitable user folder for a specific purpose
public static bool TryGetUserFolder(Folder folder, out string? userFolderPath)
Parameters
folderFolderThe type of folder to get
userFolderPathstringThe path to the user folder, when this method returns
true; otherwise,null
Returns
- bool
true, if the user folder was retrieved successfully; otherwise,false(check TryGet(out string?) for more information)
Remarks
Many operating systems provide certain standard folders for certain purposes, such as storing pictures, music or videos for a certain user. This method retrieves the paths to for many of those special locations.
This method is specifically for user folders, which are meant for the user to access and manage. For application-specific folders, meant to hold data for the application to manage, see BasePath and TryGetPreferencesPath(string?, string, out string?).
The resulting userFolderPath is guaranteed to end with a directory separator character ('\\' on Windows; '/' on most other platforms).
TryGlobDirectory(string, string?, GlobFlags, out string[]?)
Tries to enumerate file system entries in a directory, filtered by a pattern
public static bool TryGlobDirectory(string path, string? pattern, GlobFlags flags, out string[]? matches)
Parameters
pathstringThe path to the directory to enumerate
patternstringThe pattern that entries must match. Can be
nullto not filter at all.flagsGlobFlagsFlags to modify the pattern matching behavior
matchesstring[]The matching file system entries, when this method returns
true; otherwise,null
Returns
- bool
true, if the directory was successfully enumerated and entries were filtered; otherwise,false(check TryGet(out string?) for more information)
Remarks
Entries are filtered out if they don't match the pattern, which may contain wildcard characters '*' (match everything) and '?' (match one character).
If pattern is null, no filtering is done and all results are returned.
Subdirectories are permitted, and are specified with a path separator of '/'. Wildcard characters '*' and '?' never match a path separator.
flags may be set to CaseInsensitive to make the pattern matching case-insensitive.
TryRemovePath(string)
Tries to remove a file or an empty directory at the specified path
public static bool TryRemovePath(string path)
Parameters
pathstringThe path to the file or directory to remove
Returns
- bool
true, if the file or directory was removed successfully; otherwise,false(check TryGet(out string?) for more information)
Remarks
Directories that are not empty will lead to this method returning false.
This method does not recursively delete directory trees.
TryRenamePath(string, string)
Tries to rename a file or directory from one path to another
public static bool TryRenamePath(string oldPath, string newPath)
Parameters
Returns
- bool
true, if the file or directory was renamed successfully; otherwise,false(check TryGet(out string?) for more information)
Remarks
If the file at newPath already exists, it will be replaced.
Note: this method will not copy files across filesystems/drives/volumes, as that is a much more complicated (and possibly time-consuming) operation.
If this method fails, you could instead TryCopyFile(string, string) to a temporary file in the same directory as newPath,
then TryRenamePath(string, string) from the temporary file to newPath and TryRemovePath(string) on oldPath, as that might work for files.
Renaming a non-empty directory across filesystems is dramatically more complex though.