我正在使用非常棘手的战斗方法:)来使像Fi?le*/Name
这样的字符串可以安全地用作File_Name
这样的文件名。
我确信有一种 cocoa 方法可以将其转换。我确信最好的提问地点就是这里:)
谢谢!
最佳答案
这将根据 Ismail 的无效字符集删除文件名中任何位置的所有无效字符(我尚未验证他的字符集有多完整)。
- (NSString *)_sanitizeFileNameString:(NSString *)fileName {
NSCharacterSet* illegalFileNameCharacters = [NSCharacterSet characterSetWithCharactersInString:@"/\\?%*|\"<>"];
return [[fileName componentsSeparatedByCharactersInSet:illegalFileNameCharacters] componentsJoinedByString:@""];
}
使用 ComponentsSeparatedByCharactersInSet 的想法归功于 Peter N Lewis:
NSString - Convert to pure alphabet only (i.e. remove accents+punctuation)
关于cocoa - 如何确保 NSString 路径(文件名)安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1281576/