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 ‑filenames method contains the paths to the files that the user selected as NSString objects. 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 ([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 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 the filenames array.

As @VenoMKO points out, the ‑filenames method is now deprecated and you should use the ‑URLs method instead. This will return an array of file NSURL objects rather than an array of NSStrings. Since pretty much all the file handling APIs in Snow Leopard were revised to take URLs, this would be the preferred option.

其他提示

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

You Want to Get File Path Using 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];
                 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top