How to get the list of directores in NSDocumentDirectory?

梦想的初衷 提交于 2019-12-03 09:06:16

Here is the code:

NSString *documentDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// create directory named "test"
[[NSFileManager defaultManager] createDirectoryAtPath:[documentDirPath stringByAppendingPathComponent:@"test"] withIntermediateDirectories:YES attributes:nil error:nil];
// retrieved all directories
NSLog(@"%@", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirPath error:nil]);

 NSArray *paths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirPath error:nil];
 BOOL isDir = NO;
 for (NSString *path in paths) {
     if ([fileManager fileExistsAtPath:path isDirectory:&isDir] && isDir) {
         // path is directory
     }
}

You could always enumerate the contents of the top level directory using -fileExistsAtPath:isDirectory: like this:

NSFileManager *sharedFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *files = [sharedFileManager enumeratorAtPath:yourPath];

for (NSString *path in files) {
    BOOL isDirectory = NO;
    [sharedFileManager fileExistsAtPath:path isDirectory:&isDirectory];
    if (isDirectory) {
        // you found a directory, so do what you will with it
    }
}

You can do this with few simple lines of code

NSString *documentDirectoryPath = // Initialize with Documents path
BOOL isDir = NO;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *files = [fileManager contentsOfDirectoryAtPath:documentDirectoryPath error:NULL];

NSMutableArray *directoriesPaths = [NSMutableArray array];
for (NSString *filePath in files) {
    if ([fileManager fileExistsAtPath:filePath isDirectory:&isDir] && isDir) {
        [directoriesPaths addObject:filePath];
    }
}

NSLog(@"directories %@", directoriesPaths);

try this,

 NSArray *arrPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *strFilePath = [[arrPath objectAtIndex:0] 
[[NSFileManager defaultManager] createDirectoryAtPath:[strFilePath stringByAppendingPathComponent:@"Sample"] withIntermediateDirectories:YES attributes:nil error:nil];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!