Tsukasa
Tsukasa

Reputation: 6552

Get directory path from full filepath

New to objective-c. How do I get the directory from a full file path?

so if I have

/User/Test/Desktop/test.txt 

I want

/User/Test

Also is there an equivalent to Path.Combine from .NET in Objective-C?

Upvotes: 2

Views: 2547

Answers (2)

CRD
CRD

Reputation: 53000

Read the Working with Paths section of Apple's NSString documentation, you will find methods that answer your questions. For example, stringByDeletingLastPathComponent removes the last component of a path leaving the containing directory.

Upvotes: 4

Gabriele Petronella
Gabriele Petronella

Reputation: 108091

-[NSString pathComponents] returns an NSArray of path components.

For instance

NSString *path = @"/User/Test/Desktop/test.txt";
NSArray *components = [path pathComponents];
NSLog(@"%@", components); //=> ( /, User, Test, Desktop, test.txt )

Then you can take only the components you need and build a new path with them, for instance

NSString *newPath =
    [NSString pathWithComponents:
        [components subarrayWithRange:(NSRange){ 0, components.count - 2}]];
NSLog(@"%@", newPath); // => /User/Test/

Upvotes: 4

Related Questions