I have a File Open Dialog box in my application to select files from, but when the user clicks the ‘Select’ button in the box, it obviously won’t do anything. How do I extract the filepath from the selected file? I need the filepath so I can get the contents of the file to encrypt. Initially, I hard coded the file I would use into my application, but that was only for testing purposes. Here is what I am using for the File Open Dialog Box:
int i;
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:YES];
[openDlg setPrompt:@"Select"];
NSString *fileName = [pathAsNSString lastPathComponent];
[fileName stringByDeletingPathExtension];
if ([openDlg runModalForDirectory:nil file:nil] == NSOKButton )
{
NSArray* files = [openDlg filenames];
for( i = 0; i < [files count]; i++ )
{
[files objectAtIndex:i];
}
}
Thanks so much for the help.
Your code is already handling the files that the user has selected, you’re just not doing anything with them.
The array returned from the
‑filenamesmethod contains the paths to the files that the user selected asNSStringobjects. If they have only selected one file, there will only be one object in the array. If they have selected no files, the array will be empty.If you only want the user to be able to select a single file, then call
[openPanel setAllowsMultipleSelection:NO]when you’re configuring the panel. That way, there will be a maximum of one entry in thefilenamesarray.As @VenoMKO points out, the
‑filenamesmethod is now deprecated and you should use the‑URLsmethod instead. This will return an array of fileNSURLobjects rather than an array ofNSStrings. Since pretty much all the file handling APIs in Snow Leopard were revised to take URLs, this would be the preferred option.