Get File Open File Cocoa Dialog Box?

I have an “Open file” dialog box in the application for selecting files, but when the user clicks the “Select” button in the field, this obviously will not do anything. How to extract file path from selected file? I need a file path, so I can get the contents of the file for encryption. Initially, I hardcoded the file that I would use in my application, but this was only for testing purposes. Here is what I use 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]; } } 

Thank you for help.

+4
source share
3 answers

Your code already processes the files that the user selected, you just do nothing with them.

The array returned from the ‑filenames method contains the paths to the files that the user ‑filenames as NSString objects. If they selected only one file, there will be only one object in the array. If they did not select files, the array will be empty.

 if ([openDlg runModalForDirectory:nil file:nil] == NSOKButton ) { NSArray* files = [openDlg filenames]; for(NSString* filePath in [openDlg filenames]) { NSLog(@"%@",filePath); //do something with the file at filePath } } 

If you want the user to be able to select a single file, call [openPanel setAllowsMultipleSelection:NO] when you configure the panel. Thus, there will be a maximum of one entry in the filenames array.

As @VenoMKO points out, the ‑filenames method ‑filenames now deprecated, and you should use the ‑URLs method ‑URLs . This will return an array of NSURL files, not an NSString s array. Since almost all of the file processing APIs in Snow Leopard have been revised to use URLs, this would be the preferred option.

+1
source

Use the - (NSArray *)URLs method instead of filenames .

+5
source

You want to get the file path using the following code

  NSOpenPanel* openPanel = [NSOpenPanel openPanel]; [openPanel setCanChooseFiles:YES]; [openPanel setCanChooseDirectories:NO]; [openPanel setAllowsMultipleSelection: NO]; [openPanel setAllowedFileTypes:ArrExtension ]; if ([openPanel runModal] == NSOKButton ){ NSString *FilePath = [NSString stringWithFormat:@"%@",[openPanel URL]]; [openPanel canHide]; } 
0
source

All Articles