Get filename and extension from filepath programmatically cocoa?
Asked Answered
S

4

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!

Sudarium answered 28/8, 2011 at 18:39 Comment(0)
J
45

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

Jorgejorgensen answered 28/8, 2011 at 18:42 Comment(0)
N
29

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

Noella answered 10/10, 2012 at 15:29 Comment(0)
S
0

Try this, it works for me.

NSString *fileName = @"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
Snuff answered 31/3, 2017 at 19:56 Comment(0)
S
-3

i hope this will help you....

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

  [txtBeowsFilePath setStringValue:Str];

  Browesfilename=[Str lastPathComponent];
Sinkage answered 19/8, 2014 at 8:35 Comment(3)
It's poor practice to name your local variables starting with capital letters. You should name them 'filePath' and 'extension' not 'FilePath' and 'Extension'.Veriee
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)Respiration
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.Vlaminck

© 2022 - 2024 — McMap. All rights reserved.