Reputation: 4271
i need to get all files in a directory, including all sub directories and all files in each subdirectory. in objective C, i have try to use this method
[[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:nil]
but it just give me an array of contents file in directory filePath, i cant get all files in the sub directory, can somebody help me??
thank you
Upvotes: 6
Views: 7549
Reputation: 2973
You want to use enumeratorAtURL:includingPropertiesForKeys:options:error: instead. It does a deep enumeration by default:
NSURL *myDirectoryURL = [[NSBundle mainBundle] URLForResource:@"Assets" withExtension:@""];
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:myDirectoryURL includingPropertiesForKeys:[NSArray array] options:0 errorHandler:^BOOL(NSURL *url, NSError *error) {
// handle error
return NO;
}];
NSString *fileOrDirectory = nil;
while ((fileOrDirectory = [directoryEnumerator nextObject])) {
// use file or directory
}
The options argument lets you specify deep or shallow enumeration.
Upvotes: 5
Reputation: 1528
- (void)scanPath:(NSString *) sPath {
BOOL isDir;
[[NSFileManager defaultManager] fileExistsAtPath:sPath isDirectory:&isDir];
if(isDir)
{
NSArray *contentOfDirectory=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:sPath error:NULL];
int contentcount = [contentOfDirectory count];
int i;
for(i=0;i<contentcount;i++)
{
NSString *fileName = [contentOfDirectory objectAtIndex:i];
NSString *path = [sPath stringByAppendingFormat:@"%@%@",@"/",fileName];
if([[NSFileManager defaultManager] isDeletableFileAtPath:path])
{
NSLog(path);
[self scanPath:path];
}
}
}
else
{
NSString *msg=[NSString stringWithFormat:@"%@",sPath];
NSLog(msg);
}
}
you can call this function which will log all the files in the directory, hope this will help.
Upvotes: 9