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 Answers4

45

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

Rob Keniger
  • 45,830
  • 6
  • 101
  • 134
chmeee
  • 3,608
  • 1
  • 21
  • 28
29

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

codercat
  • 22,873
  • 9
  • 61
  • 85
Fabio Napodano
  • 1,210
  • 1
  • 16
  • 17
0

Try this, it works for me.

NSString *fileName = @"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
Ashu
  • 3,373
  • 38
  • 34
-3

i hope this will help you....

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

  [txtBeowsFilePath setStringValue:Str];

  Browesfilename=[Str lastPathComponent];
codercat
  • 22,873
  • 9
  • 61
  • 85
  • 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'. – Oliver Cooper Apr 05 '15 at 02: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 '15 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. – Alex Zavatone Oct 30 '16 at 18:32