如何删除应用程序上指定目录中的所有文件?

时间:2010-02-09 03:40:31

标签: iphone objective-c cocoa-touch filesystems

给定目录[[self documentsDirectory] stringByAppendingPathComponent:@"Photos/"]如何删除此文件夹中的所有文件?

(假设文档目录路径正确)

5 个答案:

答案 0 :(得分:114)

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

如果它存在,我会留下你对错误做一些有用的事情。

答案 1 :(得分:16)

如果要删除文件和目录本身,请在没有for循环

的情况下使用它
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
}

答案 2 :(得分:13)

对于快速爱好者来说同样如此:

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

答案 3 :(得分:2)

大部分较旧的答案都让您使用contentsOfDirectoryAtPath:error:,但according to Apple

  

"指定文件或目录位置的首选方法是使用NSURL类"

所以如果你想使用NSURL,你可以使用方法contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error:,所以它看起来像这样:

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

答案 4 :(得分:0)

Swift 4

  do {

        let destinationLocation:URL = ...

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

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