NSFileManager delete contents of directory

后端 未结 9 1729
你的背包
你的背包 2021-01-30 17:13

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.

相关标签:
9条回答
  • 2021-01-30 17:50

    The documentation for contentsOfDirectoryAtPath:error: says:

    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.

    Thus:

    ---( file != @"." && file != @".." )---
    

    is irrelevant.

    0 讨论(0)
  • 2021-01-30 17:51

    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)
        }
    }
    
    0 讨论(0)
  • 2021-01-30 17:53

    Georg Fritzsche answer for Swift did not work for me. Instead of reading the enumerated object as a String, read it as NSURL.

    let fileManager = NSFileManager.defaultManager()
    let url = NSURL(string: "foo/bar")
    let enumerator = fileManager.enumeratorAtURL(url, includingPropertiesForKeys: nil, options: nil, errorHandler: nil)
    while let file = enumerator?.nextObject() as? NSURL {
        fileManager.removeItemAtURL(file, error: nil)
    }
    
    0 讨论(0)
提交回复
热议问题