Delete all files and folder from a certain folder
10,581
Solution 1
Your code ([fm removeItemAtPath:directory error:&error];
) should do it. If it doesn't, inspect the error it returns. If there's no error, but you still see files/subfolders - file a bug report!
Solution 2
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"urDirectory/"];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error];
if (!success || error) {
// it failed.
}
}
Hope this helps
Comments
-
SnK almost 2 years
I have a /Documents/Images folder , in that folder are several other folders named after years , in those folders i have images. I want to delete everything from the images folder ( including the folders and the images in these folders).
I tried several code snippets but none delete the folders
my method:
- (void) clearCache:(NSString *) folderName{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSFileManager *fm = [NSFileManager defaultManager]; NSString *directory = [documentsDirectoryPath stringByAppendingPathComponent:folderName]; NSLog(@"Removing items at path: %@",directory); NSError *error = nil; BOOL succes = [fm removeItemAtPath:directory error:&error]; /*for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) { //BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error]; BOOL success = [fm removeItemAtPath:[directory stringByAppendingPathComponent:file] error:&error]; if (!success || error) { // it failed. } }*/
}
-
Leena over 9 yearspossible duplicate of How to delete ALL FILES in a specified directory on the app?
-
-
Basil Bourque about 10 yearsDid you intend
documentsDirectory
to beNSDocumentDirectory
?