< Previous PageNext Page > Hide TOC

Retrieving Information About Files

This document explains how to use NSWorkspace to retrieve information about files.

Contents:

Finding File Types and Applications
Retrieving Icons


Finding File Types and Applications

To retrieve the file type and what application opens a file, use NSWorkspace’s getInfoForFile:application:type: method. The string passed to the method must be the full pathname of the desired file. This code fragment retrieves the application and type for the file at fullPath:

NSString *fullPath;    // Assume this exists.
NSString *theApplication;
NSString *theType;
 
[[NSWorkspace sharedWorkspace] getInfoForFile:fullPath
                               application:&theApplication
                               type:&theType];
[theApplication retain];
[theType retain];

To retrieve other file information, use the NSFileManager methods displayNameAtPath:, fileExtensionHidden, fileHFSCreatorCode, fileHFSTypeCode, and fileAttributesAtPath:traverseLink:.

To retrieve the full pathname for an application, use the fullPathForApplication: method, available in both languages. The provided application name can either include or omit the .app extension.

To find out if a pathname points to a file package, use the isFilePackageAtPath: method.

Retrieving Icons

The methods iconForFile: and iconForFiles: retrieve the icon for a file or the icons for an NSArray of files. Files should be specified with full pathnames. The iconForFileType: method provides the icon for a given file extension or encoded HFS file type. This code fragment retrieves the icon for the file at fullPath, and resizes it to full 128 pixels by 128 pixels resolution:

NSString *fullPath;    // Assume this exists.
NSImage *theIcon;
 
theIcon = [[[NSWorkspace sharedWorkspace] iconForFile:fullPath] retain];
[theIcon setSize:NSMakeSize(128.0,128.0)];

To retrieve a generic icon, call the NSFileTypeForHFSTypeCode function with one of the icon constants defined by Icon Services in the Carbon framework (see “Standard Finder Icon Constants” in Icon Services and Utilities Reference), then use the iconForFileType: method with the result. This code fragment retrieves the generic application icon at full size:

#import <Carbon/Carbon.h>
// ...
NSImage *theIcon;
 
theIcon = [[[NSWorkspace sharedWorkspace]
              iconForFileType:
              NSFileTypeForHFSTypeCode(kGenericApplicationIcon)] retain];
[theIcon setSize:NSMakeSize(128.0,128.0)];


< Previous PageNext Page > Hide TOC


© 2002, 2007 Apple Inc. All Rights Reserved. (Last updated: 2007-03-06)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.