Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove file types from Documents Directory

i am trying to delete all the files in the Document Directory with the extension ".jpg", after many tries, i am still not managed to succeed.

the code i have already now is:

-(void)removeOneImage:(NSString*)fileName {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg", fileName]];
[fileManager removeItemAtPath: fullPath error:NULL];
}

with this code i can remove one file with a specific name.

Can anyone help me to remove all files with a specific extension?

Kind regards,

Snowy

like image 659
Snowy Avatar asked Apr 28 '11 13:04

Snowy


2 Answers

    NSString *extension = @"jpg";
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];  
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {

    if ([[filename pathExtension] isEqualToString:extension]) {

        [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
    }
}
like image 181
Francis McGrew Avatar answered Oct 01 '22 11:10

Francis McGrew


// Get the Documents directory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];

// Delete the file using NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:[documentsDirectoryPath stringByAppendingPathComponent:yourFile.txt] error:nil];

For More information

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

like image 34
Chetan Bhalara Avatar answered Oct 01 '22 13:10

Chetan Bhalara