Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete ALL FILES in a specified directory on the app?

Given a directory [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"] how do I delete ALL FILES in this folder?

(assume a correct documents directory path)

like image 722
RexOnRoids Avatar asked Feb 09 '10 03:02

RexOnRoids


People also ask

Which command is used to delete all files in a directory?

Use the rm command to remove files you no longer need. The rm command removes the entries for a specified file, group of files, or certain select files from a list within a directory.

How do I Delete mass amounts of files?

Navigate to the folder that you want to delete (with all its files and subfolders). Use cd *path*, for example, cd C:\Trash\Files\ to do so. Use cd .. to navigate to the parent folder and run the command RMDIR /Q/S *foldername* to delete the folder and all of its subfolders.


2 Answers

NSFileManager *fm = [NSFileManager defaultManager]; NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"]; 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.     } } 

I leave it up to you to do something useful with the error if it exists.

like image 64
coneybeare Avatar answered Sep 25 '22 12:09

coneybeare


if you want to remove files and the directory itself then use it without for loop

NSFileManager *fm = [NSFileManager defaultManager]; NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos"]; NSError *error = nil; BOOL success = [fm removeItemAtPath:cacheImageDirectory error:&error]; if (!success || error) {     // something went wrong } 
like image 33
beryllium Avatar answered Sep 26 '22 12:09

beryllium