nick130586
nick130586

Reputation: 841

NSFileManager fileExistsAtPath:isDirectory usage

I'm trying to use NSFileManager to determine if an item is a file or a subdirectory.

This is what I have:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];

NSError *error = nil;
NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[documentsDir stringByAppendingPathComponent:@"exported"] error:&error];

for (NSString *filename in files) {
    NSString *path = [documentsDir stringByAppendingPathComponent:filename];        
    BOOL isDir;
    if([[NSFileManager defaultManager] fileExistsAtPath:documentsDir isDirectory:&isDir] && isDir){
        NSLog(@"%@ is a directory", path);  
    }
    else {
        NSLog (@"%@ is a file", path);
    }
}

I get "is a directory" for files as well as for subdirectories. I searched for similar SO questions and I see no difference between the code I found there and the code I'm trying to use.

Upvotes: 1

Views: 2316

Answers (1)

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

It seems you are using the wrong path to test your files and directories

In your fileExistsAtPath: you are testing for documentsDir and not path

Correct this

if([[NSFileManager defaultManager] fileExistsAtPath:documentsDir isDirectory:&isDir] && isDir)

To

if([[NSFileManager defaultManager] fileExistsAtPath: path isDirectory:&isDir] && isDir)

Upvotes: 4

Related Questions