Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFileManager delete contents of directory

How do you delete all the contents of a directory without deleting the directory itself? I want to basically empty a folder yet leave it (and the permissions) intact.

like image 777
Vervious Avatar asked May 05 '10 01:05

Vervious


3 Answers

E.g. by using a directory enumerator:

NSFileManager *fileManager = [[NSFileManager alloc] init];
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtPath:path];    
NSString *file;

while (file = [enumerator nextObject]) {
    NSError *error = nil;
    BOOL result = [fileManager removeItemAtPath:[path stringByAppendingPathComponent:file] error:&error];

    if (!result && error) {
        NSLog(@"Error: %@", error);
    }
}

Swift

let fileManager = NSFileManager.defaultManager()
let enumerator = fileManager.enumeratorAtURL(cacheURL, includingPropertiesForKeys: nil, options: nil, errorHandler: nil)

while let file = enumerator?.nextObject() as? String {
    fileManager.removeItemAtURL(cacheURL.URLByAppendingPathComponent(file), error: nil)
}
like image 51
Georg Fritzsche Avatar answered Oct 01 '22 17:10

Georg Fritzsche


Try this:

NSFileManager *manager = [NSFileManager defaultManager];
NSString *dirToEmpty = ... //directory to empty
NSError *error = nil;
NSArray *files = [manager contentsOfDirectoryAtPath:dirToEmpty 
                                              error:&error];

if(error) {
  //deal with error and bail.
}

for(NSString *file in files) {
    [manager removeItemAtPath:[dirToEmpty stringByAppendingPathComponent:file]
                        error:&error];
    if(error) {
       //an error occurred...
    }
}    
like image 39
Jacob Relkin Avatar answered Oct 01 '22 15:10

Jacob Relkin


in swift 2.0:

if let enumerator = NSFileManager.defaultManager().enumeratorAtPath(dataPath) {
  while let fileName = enumerator.nextObject() as? String {
    do {
        try NSFileManager.defaultManager().removeItemAtPath("\(dataPath)\(fileName)")
    }
    catch let e as NSError {
      print(e)
    }
    catch {
      print("error")
    }
  }
}
like image 5
Max Avatar answered Oct 01 '22 16:10

Max