How to open a folder?

Viewed 8986

After save a file I want to open the folder of saved file. How do I do that? Thank you very much!

3 Answers

If I understand your question, you want to open the folder into which something was saved in the Finder?

This should do the trick -- it assumes that you have a reference to the savePanel.

NSURL *fileURL = [savePanel URL];
NSURL *folderURL = [fileURL URLByDeletingLastPathComponent];
[[NSWorkspace sharedWorkspace] openURL: folderURL]; 

If you are starting with an NSString containing the path, then start with:

NSURL *fileURL = [NSURL fileURLWithPath: stringContainingPath];

Even better would be to not just open the folder, but have the saved file selected. NSWorkspace can do that for you:

[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:
   @[ URLToSavedFile ]];

The argument is an array of URLs, so if you have only one file you want to reveal, you simply pass an array of one object.

If, for some reason, you're targeting a version of Mac OS X older than 10.6, you'd use the older path-based method instead:

[[NSWorkspace sharedWorkspace] selectFile:pathToSavedFile 
                 inFileViewerRootedAtPath:@""];

(You want to pass an empty string for the second argument so that the Finder will reuse an existing Finder window for the folder, if there is one.)

Related