How to delete ALL FILES in a specified directory o

2019-01-17 02:50发布

问题:

Given a directory [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"] how do I delete ALL FILES in this folder?

(assume a correct documents directory path)

回答1:

NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
    BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error];
    if (!success || error) {
        // it failed.
    }
}

I leave it up to you to do something useful with the error if it exists.



回答2:

if you want to remove files and the directory itself then use it without for loop

NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"Photos"];
NSError *error = nil;
BOOL success = [fm removeItemAtPath:cacheImageDirectory error:&error];
if (!success || error) {
    // something went wrong
}


回答3:

same for swift lovers:

let fm = FileManager.default
do {
  let folderPath = "...my/folder/path"
  let paths = try fm.contentsOfDirectory(atPath: folderPath)
  for path in paths
  {
    try fm.removeItem(atPath: "\(folderPath)/\(path)")
  }
} catch {
  print(error.localizedDescription)
}


回答4:

Most of the older answers have you use contentsOfDirectoryAtPath:error: which will work, but according to Apple:

"The preferred way to specify the location of a file or directory is to use the NSURL class"

so if you want to use NSURL instead you can use the method contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: so it would look something like this:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray<NSURL*> *urls = [fileManager contentsOfDirectoryAtURL:directoryURL includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];

    for (NSURL *url in urls)
    {
        NSError *error = nil;
        BOOL success = [fileManager removeItemAtURL:url error:error];
        if (!success || error) {
            // something went wrong
        }
    }


回答5:

Swift 4

  do {

        let destinationLocation:URL = ...

        if FileManager.default.fileExists(atPath: destinationLocation.path) {
            try! FileManager.default.removeItem(at: destinationLocation)
        }

    } catch {
    print("Error \(error.localizedDescription)")
    }