Before you can open a file, you first have to locate it in the file system. The system frameworks provide many routines for obtaining references to many well-known directories, such as the
Library directory and its contents. You can also specify locations manually by building a URL or string-based path from known directory names.
When you know the location of a file, you can then start planning the best way to access it. Depending on the type of file, you may have several options. For known file types, you typically use built-in system routines to read or write the file contents and give you an object that you can use. For custom file types, you may need to read the raw file data yourself.
Choose the Right Way to Access Files
Feb 28, 2020 For: Premium Import your local files to the Spotify desktop app (see 'Desktop' instructions above). Add the files to a new playlist in the desktop app: Click New Playlist in the menu on the left.; Give your playlist a name and click CREATE.; Drag and drop your local files into this playlist.
Although you can open any file and read its contents as a stream of bytes, doing so is not always the right choice. macOS and iOS provide built-in support that makes opening many types of standard file formats (such as text files, images, sounds, and property lists) much easier. For these standard file formats, use the higher-level options for reading and writing the file contents. Table 2-1 lists the common file types supported by the system along with information about how you access them.
In situations where the standard file formats are insufficient, you can always create your own custom file formats. When reading and writing the content of custom files, you read and write data as a stream of bytes and apply those bytes to your app’s file-related data structures. You have complete control over how you read and write the bytes and how you manage your file-related data structures. For more information about the techniques for reading and writing files that use custom file formats, see Techniques for Reading and Writing Files Without File Coordinators.
Specifying the Path to a File or Directory
The preferred way to specify the location of a file or directory is to use the
NSURL class. Although the NSString class has many methods related to path creation, URLs offer a more robust way to locate files and directories. For apps that also work with network resources, URLs also mean that you can use one type of object to manage items located on a local file system or on a network server.
Note: In addition to
NSURL , you can also use the CFURLRef opaque type to manipulate paths as URLs. The NSURL class is toll-free bridged with the CFURLRef type, which means you can use them interchangeably in your code. For more information about how to create and manipulate URLs using Core Foundation, see CFURL Reference.
For most URLs, you build the URL by concatenating directory and file names together using the appropriate
NSURL methods until you have the path to the item. A URL built in that way is referred to as a path-based URL because it stores the names needed to traverse the directory hierarchy to locate the item. (You also build string-based paths by concatenating directory and file-names together, with the results stored in a slightly different format than that used by the NSURL class.) In addition to path-based URLs, you can also create a file reference URL, which identifies the location of the file or directory using a unique ID.
All of the following entries are valid references to a file called
MyFile.txt in a user’s Documents directory:
Path-based URL:
file://localhost/Users/steve/Documents/MyFile.txt
File reference URL:
file:///.file/id=6571367.2773272/ Intuit personal accounting software.
String-based path:
/Users/steve/Documents/MyFile.txt
You create URL objects using the
NSURL methods and convert them to file reference URLs only when needed. Path-based URLs are easier to manipulate, easier to debug, and are generally preferred by classes such as NSFileManager . An advantage of file reference URLs is that they are less fragile than path-based URLs while your app is running. If the user moves a file in the Finder, any path-based URLs that refer to the file immediately become invalid and must be updated to the new path. However, as long as the file moved to another location on the same disk, its unique ID does not change and any file reference URLs remain valid.
Important: Although they are safe to use while your app is running, file reference URLs are not safe to store and reuse between launches of your app because a file’s ID may change if the system is rebooted. If you want to store the location of a file persistently between launches of your app, create a bookmark as described in Locating Files Using Bookmarks.
Of course, there are still times when you might need to use strings to refer to a file. Fortunately, the
NSURL class provides methods to convert path-based URLs to and from NSString objects. You might use a string-based path when presenting that path to the user or when calling a system routine that accepts strings instead of URLs. The conversion between NSURL objects and NSString objects is done using the NSURL class’s method absoluteString .
Because
NSURL and NSString describe only the location of a file or directory, you can create them before the actual file or directory exists. Neither class attempts to validate the actual existence of the file or directory you specify. In fact, you must create the path to a nonexistent file or directory before you can create it on disk.
If you have an
NSURL object that refers to an actual file or directory on disk, and you want to get the user visible name of the volume on which it resides, you use the method getResourceValue:forKey:error: in a two step process:
Use the
NSURLLocalizedNameKey constant rather than the NSURLNameKey constant. Using NSURLNameKey returns the name of the volume in the file system, which may not be the same as the user visible name. Listing 2-1 demonstrates this process for the current user’s home directory.
Listing 2-1 Obtaining the user visible volume name for a resource URL
For more information about the methods you use to create and manipulate URLs and strings, see NSURL Class Reference and NSString Class Reference.
Locating Items in the File System![]()
Before you can access a file or directory, you need to know its location. There are several ways to locate files and directories:
The file systems of iOS and macOS impose specific guidelines on where you should place files, so most of the items your app creates or uses should be stored in a well-known place. Both systems provide interfaces for locating items in such well-known places, and your app can use these interfaces to locate items and build paths to specific files. An app should prompt the user to specify the location of a file or directory only in a limited number of situations that are described in Using the Open and Save Panels.
Asking the User to Locate an Item
In macOS, user interactions with the file system should always be through the standard Open and Save panels. Because these panels involve interrupting the user, use them only in a limited number of situations:
Never use the Open and Save panels to access any files that your app created and uses internally. Support files, caches, and app-generated data files should be placed in one of the standard directories dedicated to app-specific files.
For information on how to present and customize the Open and Save panels, see Using the Open and Save Panels.
Locating Items in Your App Bundle
Apps that need to locate resource files inside their bundle directory (or inside another known bundle) must do so using an
NSBundle object. Bundles eliminate the need for your app to remember the location of individual files by organizing those files in a specific way. The methods of the NSBundle class understand that organization and use it to locate your app’s resources on demand. The advantage of this technique is that you can generally rearrange the contents of your bundle without rewriting the code you use to access it. Bundles also take advantage of the current user’s language settings to locate an appropriately localized version of a resource file.
The following code shows how to retrieve a URL object for an image named
MyImage.png that is located in the app’s main bundle. This code determines only the location of the file; it does not open the file. You would pass the returned URL to a method of the NSImage class to load the image from disk so that you could use it.
For more information about bundles, including how to locate items in a bundle, see Bundle Programming Guide. For specific information about loading and using resources in your app, see Resource Programming Guide.
Locating Items in the Standard Directories
When you need to locate a file in one of the standard directories, use the system frameworks to locate the directory first and then use the resulting URL to build a path to the file. The Foundation framework includes several options for locating the standard system directories. By using these methods, the paths will be correct whether your app is sandboxed or not:
You can use the URL or path-based string you receive from the preceding routines to build new objects with the locations of the files you want. Both the
NSURL and NSString classes provide path-related methods for adding and removing path components and making changes to the path in general. Listing 2-2 shows an example that searches for the standard Application Support directory and creates a new URL for a directory containing the app’s data files.
Listing 2-2 Creating a URL for an item in the app support directory
Locating Files Using Bookmarks
If you want to save the location of a file persistently, use the bookmark capabilities of
NSURL . A bookmark is an opaque data structure, enclosed in an NSData object, that describes the location of a file. Whereas path- and file reference URLs are potentially fragile between launches of your app, a bookmark can usually be used to re-create a URL to a file even in cases where the file was moved or renamed.
To create a bookmark for an existing URL, use the
bookmarkDataWithOptions:includingResourceValuesForKeys:relativeToURL:error: method of NSURL . Specifying the NSURLBookmarkCreationSuitableForBookmarkFile option creates an NSData object suitable for saving to disk. Listing 2-3 shows a simple example implementation that uses this method to create a bookmark data object.
Listing 2-3 Converting a URL to a persistent form
If you write the persistent bookmark data to disk using the
writeBookmarkData:toURL:options:error: method of NSURL , what the system creates on disk is an alias file. Aliases are similar to symbolic links but are implemented differently. Normally, users create aliases from the Finder when they want to create links to files elsewhere on the system.
To transform a bookmark data object back into a URL, use the
URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error: method of NSURL . Listing 2-4 shows the process for converting a bookmark back into a URL.
Listing 2-4 Returning a persistent bookmark to its URL form
The Core Foundation framework provides a set of C-based functions that parallel the bookmark interface provided by
NSURL . For more information about using those functions, see CFURL Reference.
Enumerating the Contents of a Directory
To discover the contents of a given directory, you enumerate that directory. Cocoa supports enumerating a directory one file at a time or all at once. Regardless of which option you choose, enumerate directories sparingly. Each enumeration can touch a large number of files and subdirectories. This quickly becomes expensive.
Enumerating a Directory One File at a Time
Enumerating a directory one file at a time is recommended when you want to search for a specific file and stop enumerating when you find it. File-by-file enumeration uses the
NSDirectoryEnumerator class, which defines the methods for retrieving items. Because NSDirectoryEnumerator itself is an abstract class, however, you do not create instances of it directly. Instead, you use either the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: or the enumeratorAtPath: method of NSFileManager object to obtain a concrete instance of the class for use in your enumeration.
Enumerator objects return the paths of all files and directories contained within the enumerated directory. Because enumerations are recursive and cross device boundaries, the number of files and directories returned may be more than what is present in the starting directory. You can skip the contents of any directory you are not interested in by calling the enumerator object’s
skipDescendents method. Enumerator objects do not resolve symbolic links or attempt to traverse symbolic links that point to directories.
Listing 2-5 shows how to use the
enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: method to list all the user-visible subdirectories of a given directory, noting whether they are directories or file packages. The keys array tells the enumerator object to prefetch and cache information for each item. Prefetching this information improves efficiency by touching the disk only once. The options argument specifies that the enumeration should not list the contents of file packages and hidden files. The error handler is a block object that returns a Boolean value. If the block returns YES , the enumeration continues after the error; if it returns NO , the enumeration stops.
Listing 2-5 Enumerating the contents of a directory
You can use other methods declared by
NSDirectoryEnumerator to determine attributes of files during the enumeration—both of the parent directory and the current file or directory—and to control recursion into subdirectories. The code in Listing 2-6 enumerates the contents of a directory and lists files that have been modified within the last 24 hours; if, however, it comes across RTFD file packages, it skips recursion into them.
Listing 2-6 Looking for files that have been modified recently
Getting the Contents of a Directory in a Single Batch Operation
If you know that you want to look at every item in a directory, you can retrieve a snapshot of the items and iterate over them at your convenience. Retrieving the contents of a directory in a batch operation is not the most efficient way to enumerate a directory, because the file manager must walk the entire directory contents every time. However, if you plan to look at all the items anyway, it is a much simpler way to retrieve the items.
There are two options for doing a batch enumeration of a directory using
NSFileManager :
Listing 2-7 shows an example that uses the
contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: method to enumerate the contents of a directory. One of the benefits of using URLs is that you can also efficiently retrieve additional information about each item. This example retrieves the localized name, creation date, and type information for each item in the directory and stores that information in the corresponding NSURL object. When the method returns, you can proceed to iterate over the items in the array variable and do what you need with them.
Listing 2-7 Retrieving the list of items in a directory all at once
Determining Where to Store Your App-Specific Files
The
Library directory is the designated repository for files your app creates and manages on behalf of the user. Consider that these directories may be in different locations if your app is sandboxed. As a result, always use the NSFileManager method URLsForDirectory:inDomains: with the NSUserDomainMask as the domain to locate the specific directory that you should use to store this data.
Note: Apps rarely share the files stored in the
Application Support , Caches or Temp directories. Therefore, you don’t typically need to use a file coordinator (NSFileCoordinator ) when reading or writing to these locations. For more information about file coordination, see The Role of File Coordinators and Presenters.
Tips for Accessing Files and Directories
Because the file system is a resource shared by all processes, including system processes, use it carefully. Even on systems with solid-state disk drives, file operations tend to be a little slower because of the latency involved in retrieving data from the disk. And when you do access files, it is important that you do so in a way that is secure and does not interfere with other processes.
Perform File Operations Lazily
Operations involving the file system should be performed only when they are absolutely necessary. Accessing the file system usually takes a lot of time relative to other computer-wide tasks. So make sure you really need to access the disk before you do. Specifically:
Use Secure Coding Practices
There are several principles you can follow to help ensure that you do not have file-based security vulnerabilities in your program:
For additional tips and coding practices, see Race Conditions and Secure File Operations in Secure Coding Guide.
Assume Case Sensitivity for PathsAccessing Local Files From Mac App To Iphone
When searching or comparing filenames, always assume that the underlying file system is case sensitive. macOS supports many file systems that use case to differentiate between files. Even on file systems (such as APFS and HFS+) that support case insensitivity, there are still times when case may be used to compare filenames. For example, the
NSBundle class and CFBundle APIs consider case when searching bundle directories for named resources.
Include Filename Extensions for New Files
All files should have a filename extension that reflects the type of content contained in the file. Filename extensions help the system determine how to open files and also make it easier to exchange files with other computers or other platforms. For example, network transfer programs often use filename extensions to determine the best way to to transfer files between computers.
Accessing Local Files From Mac App StoreUse Display Names When Presenting Items
Whenever you need to present the name of a file or directory in your user interface, always use the item’s display name. Using the display name ensures that what your app presents matches what the Finder and other apps are presenting. For example, if your app shows the path to a file, using the display name ensures that the path is localized in accordance with the current user’s language settings.
For more information about display names, see Files and Directories Can Have Alternate Names.
Accessing Files Safely from Background Threads
In general, the objects and functions used to access and manipulate files can be used from any thread of your app. However, as with all threaded programming, make sure you manipulate files safely from your background threads:
Copyright © 2018 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2018-04-09
The Remote Desktop Connection (RDC) feature of Windows allows you to remotely view and control remote Windows desktops. Sharing resources between your local and remote PC can be tricky, but it is possible to share your local files and folders over a remote desktop session using RDC or other remote desktop tools like TightVNC.
If you’re using RDC and want to access the files and folders on your PC when you’re connected, you’ll need to configure your RDC setup. You can set this every time you connect or, alternatively, create a Remote Desktop Protocol (RDP) shortcut file to save your settings.
Accessing Local Files & Folders Over a Remote Desktop Connection
The Remote Desktop Connection tool uses Microsoft’s Remote Desktop Protocol to create a remote desktop session to Windows PCs and servers. It’s included with all editions of Windows 10 and Windows Server.
Microsoft also offers RDP-capable software to allow you to connect to Windows PCs on Mac, as well as on mobile platforms like Android and iOS. If you’re on a Mac, you can share your Mac files and folders to Windows in the Redirection tab of the Remote Desktop app.
On Windows, the built-in Remote Desktop Connection tool allows you to configure your file and folder sharing settings before you connect.
The Remote Desktop Connection tool, when first launched, is pretty basic. Normally, you would insert the IP address for your remote PC and click connect, but you’ll need to configure things further before you connect if you want to access your local files and folders.
Accessing Local Files From Mac App Windows 7
These settings may only last for the duration of your connection to your remote desktop. To save these settings, you’ll need to save your connection as a shortcut using an RDP settings file.
Saving RDC Settings With An RDP Shortcut File
Remote Desktop Protocol settings files are designed to be interchangeable with other software that allows RDP connections.
Once your RDP file is saved, you can then use it to directly connect to your remote desktop in future. Double-clicking on the file to open it will launch the RDC tool and automatically connect with your predetermined settings applied.
You can also access the file from within the Remote Desktop Connection tool by clicking Open under the Connection settings section.
If, at any point, you wish to change these settings, then follow the instructions above to overwrite the saved RDP file.
Sharing Files & Folders Over VNC
While Windows comes with the RDC tool, you can use other, third-party remote desktop connection software to connect to Windows and other operating systems. VNC is one of the more popular alternative protocols to RDP, with various connection clients you can use.
Accessing Local Files From Mac App Free
One of the most popular VNC server-client software combinations is RealVNC, but this only supports file transfers with a professional or enterprise subscription. A good, free alternative for Windows users is TightVNC, which does allow for file transfers.
You’ll need a VNC server installed on your remote desktop to be able to do this. Installing TightVNC generally installs both the server and the viewer components, unless you customize this during the setup process.
Once you agree to begin the transfer, the files and folders you’ve selected will begin copying across. If you want to cancel the transfer, click the Cancel button at the bottom of the window.
Accessing Local Files From Mac App To Pc
If you’d rather use another client, you can use file transfer software like WinSCP to move files between your local and remote Windows PCs instead.
Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |