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.

Sign up to request clarification or add additional context in comments.

Comments

29

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

Comments

0

Try this, it works for me.

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

Comments

-3

i hope this will help you....

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

  [txtBeowsFilePath setStringValue:Str];

  Browesfilename=[Str lastPathComponent];

3 Comments

It's poor practice to name your local variables starting with capital letters. You should name them 'filePath' and 'extension' not 'FilePath' and 'Extension'.
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)
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.

Your Answer

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