NSFileManager delete contents of directory

后端 未结 9 1727
你的背包
你的背包 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:32

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

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

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

    You can extend the NSFileManager like this:

    extension NSFileManager {
      func clearFolderAtPath(path: String) -> Void {
          for file in subpathsOfDirectoryAtPath(path, error: nil) as? [String] ?? []  {
              self.removeItemAtPath(path.stringByAppendingPathComponent(file), error: nil)
          }
      }
    }
    

    Then, you can clear the folder like this: NSFileManager.defaultManager().clearFolderAtPath("the folder's path")

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

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

    Why not deleting the whole directory and recreate afterwards? Just get the file attributes and permissions before deleting it, and then recreate it with the same attributes.

    0 讨论(0)
提交回复
热议问题