NSFileManager delete contents of directory

28,054

Solution 1

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)
}

Solution 2

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...
    }
}    

Solution 3

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")
    }
  }
}

Solution 4

Swift 3 if anyone needs it for a quick cut/paste

let fileManager = FileManager.default
let fileUrls = fileManager.enumerator(at: folderUrl, includingPropertiesForKeys: nil)
while let fileUrl = fileUrls?.nextObject() {
    do {
        try fileManager.removeItem(at: fileUrl as! URL)
    } catch {
        print(error)
    }
}

Solution 5

Swift 2.1.1:

public func deleteContentsOfFolder()
{
    // folderURL
    if let folderURL = self.URL()
    {
        // enumerator
        if let enumerator = NSFileManager.defaultManager().enumeratorAtURL(folderURL, includingPropertiesForKeys: nil, options: [], errorHandler: nil)
        {
            // item
            while let item = enumerator.nextObject()
            {
                // itemURL
                if let itemURL = item as? NSURL
                {
                    do
                    {
                        try NSFileManager.defaultManager().removeItemAtURL(itemURL)
                    }
                    catch let error as NSError
                    {
                        print("JBSFile Exception: Could not delete item within folder.  \(error)")
                    }
                    catch
                    {
                        print("JBSFile Exception: Could not delete item within folder.")
                    }
                }
            }
        }
    }
}
Share:
28,054
Vervious
Author by

Vervious

phd student studying cryptography and distributed algorithms You should learn Streamlet instead of Paxos! It's simpler and captures the intuition of both blockchains and consensus. See my blog post https://decentralizedthoughts.github.io/2020-05-14-streamlet/

Updated on January 18, 2020

Comments

  • Vervious
    Vervious over 4 years

    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.

  • Georg Fritzsche
    Georg Fritzsche almost 14 years
    contentsOfDirectoryAtPath:: doesn't give you the full path of the contents.
  • Nico
    Nico almost 14 years
    Don't forget to check whether removeItemAtPath: actually failed before attempting to use the error object. At the very least, you may report more errors than you actually have.
  • Psycho
    Psycho almost 13 years
    There's a problem in your while loop, you can't declare you variable inside the while parentheses !!
  • Georg Fritzsche
    Georg Fritzsche almost 13 years
    @Psycho: True for Objective-C, works fine though for Objective-C++. Worth a down-vote when this isn't related to the problem and easy to fix? I don't think so...
  • Psycho
    Psycho almost 13 years
    The down vote was for the solution, just delete the whole directory by saving the permissions instead of iterating through the content.
  • Georg Fritzsche
    Georg Fritzsche almost 13 years
    Why would you want to remove the folder and run into possible problems (e.g. permissions) if you can just remove it's contents?
  • petert
    petert over 12 years
    There is no need to test for "." or ".." since contentsOfDirectoryAtPath:error filters them out; from docs The search is shallow and therefore does not return the contents of any subdirectories. This returned array does not contain strings for the current directory (“.”), parent directory (“..”), or resource forks (begin with “._”) and does not traverse symbolic links.
  • Jacob Relkin
    Jacob Relkin over 12 years
    @petert Whoa, this is a very old answer. Thanks for the info.
  • petert
    petert over 12 years
    It's often better to scan a directory and remove files from source code since it's far more reliable to recover and report errors.