繁体   English   中英

如何删除 Documents 目录的内容(而不是 Documents 目录本身)?

[英]How to delete the contents of the Documents directory (and not the Documents directory itself)?

我想删除 Documents 目录中包含的所有文件和目录。

我相信使用[fileManager removeItemAtPath:documentsDirectoryPath error:nil]方法也会删除文档目录。

是否有任何方法可以让您仅删除目录的内容并将空目录留在那里?

尝试这个:

NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSError *error = nil;
for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error]) {
    [[NSFileManager defaultManager] removeItemAtPath:[folderPath stringByAppendingPathComponent:file] error:&error];
}

斯威夫特 3.x

let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
guard let items = try? FileManager.default.contentsOfDirectory(atPath: path) else { return }

for item in items {
    // This can be made better by using pathComponent
    let completePath = path.appending("/").appending(item)
    try? FileManager.default.removeItem(atPath: completePath)
}

我认为使用 URLs 而不是 String 使它更简单:

private func clearDocumentsDirectory() {
    let fileManager = FileManager.default
    guard let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

    let items = try? fileManager.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil)
    items?.forEach { item in
        try? fileManager.removeItem(at: item)
    }
}

其他解决方案只删除表面级别,这将迭代地撕裂到子目录并清除它们。

此外,一些答案正在使用removeItem:仅使用文件本身的本地路径而不是完整路径,这是操作系统正确删除所需的完整路径。


只需调用[self purgeDocuments];

+(void)purgeDocuments __deprecated_msg("For debug purposes only") {
    NSString *documentDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    [self purgeDirectory:documentDirectoryPath];
}

+(void)purgeDirectory:(NSString *)directoryPath __deprecated_msg("For debug purposes only") {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:directoryPath error:&error];
    for (NSString *itemPath in directoryContent) {
        NSString *itemFullPath = [NSString stringWithFormat:@"%@/%@", directoryPath, itemPath];
        BOOL isDir;
        if ([fileManager fileExistsAtPath:itemFullPath isDirectory:&isDir]) {
            if (isDir) {
                [self purgeDirectory:itemFullPath];//subdirectory
            } else {
                [fileManager removeItemAtPath:itemFullPath error:&error];
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM