7

I am trying to return the list of directories present in an app's Documents directory. I am able to get an array containing all files of a given extension (eg .txt files or .png files) and am able to return all contents (including directories). The problem arises when I want to return only the directories. Is there a simple way of doing this?

Here is my code for returning all .txt files:

- (ViewController *) init {
    if (self = [super init]) self.title = @"Text Files";

    // get the list of .txt files
    directoryList = [[[[NSFileManager defaultManager] directoryContentsAtPath:DOCUMENTS_FOLDER] 
                      pathsMatchingExtensions:[NSArray arrayWithObjects:@".txt", nil]] retain];
    NSLog(@"%@", directoryList);

    return self;
}

and for all of the files

- (ViewController *) init {
    if (self = [super init]) self.title = @"Text Files";

    // get the list of all files and directories
    directoryList = [[[NSFileManager defaultManager] directoryContentsAtPath:DOCUMENTS_FOLDER] retain];

    NSLog(@"%@", directoryList);

    return self;
}
Jack
  • 3,878
  • 15
  • 42
  • 72

2 Answers2

23

Try this:

- (ViewController *) init {
    if (self = [super init]) self.title = @"Text Files";

    // get the list of all files and directories
    NSFileManager *fM = [NSFileManager defaultManager];
    fileList = [[fM directoryContentsAtPath:DOCUMENTS_FOLDER] retain];
    NSMutableArray *directoryList = [[NSMutableArray alloc] init];
    for(NSString *file in fileList) {
        NSString *path = [DOCUMENTS_FOLDER stringByAppendingPathComponent:file];
        BOOL isDir = NO;
        [fM fileExistsAtPath:path isDirectory:(&isDir)];
        if(isDir) {
            [directoryList addObject:file];
        }
    }

    NSLog(@"%@", directoryList);

    return self;
}
mrueg
  • 8,185
  • 4
  • 44
  • 66
  • Excellent answer subw. Didn't know of the fileExistsAtPath:isDirectory: instance method; I'll have a read up of the NSFileManager documentation. – Jack Jan 31 '10 at 16:31
  • 2
    directoryContentsOfPath: is deprecated. Must be subpathsOfDirectoryAtPath: instead – DerWOK Aug 30 '13 at 15:17
  • 1
    @DerWOK Those two methods do very different things. `subpathsOfDirectoryAtPath:error:` lists subpaths **recursively**. The correct replacement for `directoryContentsAtPath:` is `contentsOfDirectoryAtPath:error:` – Daniel Rinser Jun 17 '15 at 09:32
2

Mrueg wrote it all but one thing that

fileList = [[fM directoryContentsAtPath:DOCUMENTS_FOLDER];

Replace by

fileList = [fileManager contentsOfDirectoryAtPath:filePath error:nil];
Pawandeep Singh
  • 830
  • 1
  • 13
  • 25