Class

FileManager

An object that provides a convenient interface to the contents of the file system.

Overview

An FileManager object lets you examine the contents of the file system and make changes to it. The FileManager class provides convenient access to a shared file manager object that is suitable for most types of file-related manipulations. A file manager object is typically your primary mode of interaction with the file system. You use it to locate, create, copy, and move files and directories. You also use it to get information about a file or directory or change some of its attributes.

When specifying the location of files, you can use either NSURL or NSString objects. The use of the NSURL class is generally preferred for specifying file-system items because they can convert path information to a more efficient representation internally. You can also obtain a bookmark from an NSURL object, which is similar to an alias and offers a more sure way of locating the file or directory later.

If you are moving, copying, linking, or removing files or directories, you can use a delegate in conjunction with a file manager object to manage those operations. The delegate’s role is to affirm the operation and to decide whether to proceed when errors occur. In macOS 10.7 and later, the delegate must conform to the FileManagerDelegate protocol.

In iOS 5.0 and later and in macOS 10.7 and later, FileManager includes methods for managing items stored in iCloud. Files and directories tagged for cloud storage are synced to iCloud so that they can be made available to the user’s iOS devices and Macintosh computers. Changes to an item in one location are propagated to all other locations to ensure the items stay in sync.

Threading Considerations

The methods of the shared FileManager object can be called from multiple threads safely. However, if you use a delegate to receive notifications about the status of move, copy, remove, and link operations, you should create a unique instance of the file manager object, assign your delegate to that object, and use that file manager to initiate your operations.

Topics

Creating a File Manager

class var `default`: FileManager

Returns the shared file manager object for the process.

Accessing User Directories

var temporaryDirectory: URL

Returns the temporary directory for the current user.

var homeDirectoryForCurrentUser: URL

Returns the home directory for the current user.

func homeDirectory(forUser: String)

Returns the home directory for the specified user.

Locating System Directories

func urls(for: FileManager.SearchPathDirectory, in: FileManager.SearchPathDomainMask)

Returns an array of URLs for the specified common directory in the requested domains.

Locating Application Group Container Directories

func containerURL(forSecurityApplicationGroupIdentifier: String)

Returns the container directory associated with the specified security application group identifier.

Discovering Directory Contents

func contentsOfDirectory(at: URL, includingPropertiesForKeys: [URLResourceKey]?, options: FileManager.DirectoryEnumerationOptions = [])

Performs a shallow search of the specified directory and returns URLs for the contained items.

func contentsOfDirectory(atPath: String)

Performs a shallow search of the specified directory and returns the paths of any contained items.

func enumerator(atPath: String)

Returns a directory enumerator object that can be used to perform a deep enumeration of the directory at the specified path.

class FileManager.DirectoryEnumerator

An NSDirectoryEnumerator object enumerates the contents of a directory, returning the pathnames of all files and directories contained within that directory. These pathnames are relative to the directory.

func subpathsOfDirectory(atPath: String)

Performs a deep enumeration of the specified directory and returns the paths of all of the contained subdirectories.

func subpaths(atPath: String)

Returns an array of strings identifying the paths for all items in the specified directory.

Creating and Deleting Items

func createFile(atPath: String, contents: Data?, attributes: [FileAttributeKey : Any]? = nil)

Creates a file with the specified content and attributes at the given location.

func removeItem(at: URL)

Removes the file or directory at the specified URL.

func removeItem(atPath: String)

Removes the file or directory at the specified path.

Moving and Copying Items

func copyItem(at: URL, to: URL)

Copies the file at the specified URL to a new location synchronously.

func copyItem(atPath: String, toPath: String)

Copies the item at the specified path to a new location synchronously.

func moveItem(at: URL, to: URL)

Moves the file or directory at the specified URL to a new location synchronously.

func moveItem(atPath: String, toPath: String)

Moves the file or directory at the specified path to a new location synchronously.

Managing iCloud-Based Items

var ubiquityIdentityToken: (NSCoding & NSCopying & NSObjectProtocol)?

An opaque token that represents the current user’s iCloud identity

func url(forUbiquityContainerIdentifier: String?)

Returns the URL for the iCloud container associated with the specified identifier and establishes access to that container.

func isUbiquitousItem(at: URL)

Returns a Boolean indicating whether the item is targeted for storage in iCloud.

func setUbiquitous(Bool, itemAt: URL, destinationURL: URL)

Sets whether the item at the specified URL should be stored in the cloud.

func startDownloadingUbiquitousItem(at: URL)

Starts downloading (if necessary) the specified item to the local system.

func evictUbiquitousItem(at: URL)

Removes the local copy of the specified cloud-based item.

func url(forPublishingUbiquitousItemAt: URL, expiration: AutoreleasingUnsafeMutablePointer<NSDate?>?)

Returns a URL that can be emailed to users to allow them to download a copy of a cloud-based flat file item.

Creating Symbolic and Hard Links

func createSymbolicLink(at: URL, withDestinationURL: URL)

Creates a symbolic link at the specified URL that points to an item at the given URL.

func createSymbolicLink(atPath: String, withDestinationPath: String)

Creates a symbolic link that points to the specified destination.

func linkItem(at: URL, to: URL)

Creates a hard link between the items at the specified URLs.

func linkItem(atPath: String, toPath: String)

Creates a hard link between the items at the specified paths.

func destinationOfSymbolicLink(atPath: String)

Returns the path of the item pointed to by a symbolic link.

Determining Access to Files

func fileExists(atPath: String)

Returns a Boolean value that indicates whether a file or directory exists at a specified path.

func fileExists(atPath: String, isDirectory: UnsafeMutablePointer<ObjCBool>?)

Returns a Boolean value that indicates whether a file or directory exists at a specified path. The isDirectory out parameter indicates whether the path points to a directory or a regular file.

func isReadableFile(atPath: String)

Returns a Boolean value that indicates whether the invoking object appears able to read a specified file.

func isWritableFile(atPath: String)

Returns a Boolean value that indicates whether the invoking object appears able to write to a specified file.

func isExecutableFile(atPath: String)

Returns a Boolean value that indicates whether the operating system appears able to execute a specified file.

func isDeletableFile(atPath: String)

Returns a Boolean value that indicates whether the invoking object appears able to delete a specified file.

Getting and Setting Attributes

func componentsToDisplay(forPath: String)

Returns an array of strings representing the user-visible components of a given path.

func displayName(atPath: String)

Returns the display name of the file or directory at a specified path.

func attributesOfItem(atPath: String)

Returns the attributes of the item at a given path.

func attributesOfFileSystem(forPath: String)

Returns a dictionary that describes the attributes of the mounted file system on which a given path resides.

func setAttributes([FileAttributeKey : Any], ofItemAtPath: String)

Sets the attributes of the specified file or directory.

Getting and Comparing File Contents

func contents(atPath: String)

Returns the contents of the file at the specified path.

func contentsEqual(atPath: String, andPath: String)

Returns a Boolean value that indicates whether the files or directories in specified paths have the same contents.

Getting the Relationship Between Items

Converting File Paths to Strings

func fileSystemRepresentation(withPath: String)

Returns a C-string representation of a given path that properly encodes Unicode strings for use by the file system.

func string(withFileSystemRepresentation: UnsafePointer<Int8>, length: Int)

Returns an NSString object whose contents are derived from the specified C-string path.

Managing the Delegate

var delegate: FileManagerDelegate?

The delegate of the file manager object.

Managing the Current Directory

func changeCurrentDirectoryPath(String)

Changes the path of the current working directory to the specified path.

var currentDirectoryPath: String

The path to the program’s current directory.

Deprecated Methods

func changeFileAttributes([AnyHashable : Any] = [:], atPath: String)

Changes the attributes of a given file or directory.

Deprecated
func fileAttributes(atPath: String, traverseLink: Bool)

Returns a dictionary that describes the POSIX attributes of the file specified at a given.

Deprecated
func fileSystemAttributes(atPath: String)

Returns a dictionary that describes the attributes of the mounted file system on which a given path resides.

Deprecated
func directoryContents(atPath: String)

Returns the directories and files (including symbolic links) contained in a given directory.

Deprecated
func createDirectory(atPath: String, attributes: [AnyHashable : Any] = [:])

Creates a directory (without contents) at a given path with given attributes.

Deprecated
func createSymbolicLink(atPath: String, pathContent: String)

Creates a symbolic link identified by a given path that refers to a given location.

Deprecated
func pathContentOfSymbolicLink(atPath: String)

Returns the path of the directory or file that a symbolic link at a given path refers to.

Deprecated
func fileManager(FileManager, shouldProceedAfterError: [AnyHashable : Any])

An NSFileManager object sends this message to its handler for each error it encounters when copying, moving, removing, or linking files or directories.

Deprecated
func fileManager(FileManager, willProcessPath: String)

An NSFileManager object sends this message to a handler immediately before attempting to move, copy, rename, or delete, or before attempting to link to a given path.

Deprecated

Constants

enum FileManager.SearchPathDirectory

These constants specify the location of a variety of directories by the urls(for:in:) and url(for:in:appropriateFor:create:) FileManager methods.

struct FileManager.SearchPathDomainMask

Search path domain constants specifying base locations for the FileManager.SearchPathDirectory type. These constants are used by the urls(for:in:) and url(for:in:appropriateFor:create:) FileManager methods.

struct FileAttributeKey

Keys in dictionaries used with methods listed in Getting and Setting Attributes.

struct FileAttributeType

These strings are the possible values for the type attribute key contained in the dictionary object returned by attributesOfItem(atPath:).

struct FileProtectionType

Specifies the values that can be associated with the protectionKey key.

enum FileManager.URLRelationship

Constants indicating the relationship between a directory and an item.

var NSFoundationVersionWithFileManagerResourceForkSupport: Int32

The version of the Foundation framework in which NSFileManager first supported resource forks.

File Path Functions

func NSFullUserName()

Returns a string containing the full name of the current user.

func NSHomeDirectory()

Returns the path to either the user’s or application’s home directory, depending on the platform.

func NSHomeDirectoryForUser(String?)

Returns the path to a given user’s home directory.

func NSOpenStepRootDirectory()

Returns the root directory of the user’s system.

func NSTemporaryDirectory()

Returns the path of the temporary directory for the current user.

func NSUserName()

Returns the logon name of the current user.

HFS File Type Functions

func NSFileTypeForHFSTypeCode(OSType)

Returns a string encoding a file type code.

func NSHFSTypeOfFile(String!)

Returns a string encoding a file type.

Notifications

static let NSUbiquityIdentityDidChange: NSNotification.Name

Sent after the iCloud (“ubiquity”) identity has changed.

Relationships

Inherits From

Conforms To

See Also

File System Operations

protocol FileManagerDelegate

The interface a file manager's delegate uses to intervene during operations or if an error occurs.