21

I know you can use NSBundle:

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"rtf"];

to get the filepath of a file, but how would I get the filename and extension (separately) from the filepath programmatically using NSBundle.

For example, I may have: /Users/theuser/Documents/yourdocument.txt

It is obvious that the file is 'yourdocument', and the extension 'txt'

But I need to get the filename and extension from the filepath to use as an NSString.

Your help is greatly appreciated!

4 Answers 4

45

There are methods on NSString that do this. Look at -[NSString pathExtension] and -[NSString lastPathComponent], both defined in NSPathUtilities.h.

0
29

to get the filename without extension, try out [NSString stringByDeletingPathExtension];

0

Try this, it works for me.

NSString *fileName = @"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
-3

i hope this will help you....

Str = [NSString stringWithFormat:@"%@",[openPanel URL]];

  [txtBeowsFilePath setStringValue:Str];

  Browesfilename=[Str lastPathComponent];
3
  • 1
    It's poor practice to name your local variables starting with capital letters. You should name them 'filePath' and 'extension' not 'FilePath' and 'Extension'. Apr 5, 2015 at 2:21
  • 1
    this answer is wrong, lastPathComponent will give you the entire filename as it is the last component after the slash (if it is a file)
    – NikkyD
    May 13, 2015 at 12:45
  • This is terrible coding. Do not start your variables with capital letters. Use proper spacing between assignment statements. You are also misspelling your variables different ways each time and you are arbitrarily camelcasing. NEVER do this. This is simply terrible. Oct 30, 2016 at 18:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.