How to make an NSString path (file name) safe

cocoafan picture cocoafan · Aug 15, 2009 · Viewed 15k times · Source

I'm using very tricky fighting methods :) to make a string like Fi?le*/ Name safe for using as a file name like File_Name. I'm sure there is a cocoa way to convert it. And I'm sure the best place to ask is here :)

Thank you!

Answer

johnboiles picture johnboiles · Feb 9, 2011

This will remove all invalid characters anywhere in the filename based on Ismail's invalid character set (I have not verified how complete his set is).

- (NSString *)_sanitizeFileNameString:(NSString *)fileName {
    NSCharacterSet* illegalFileNameCharacters = [NSCharacterSet characterSetWithCharactersInString:@"/\\?%*|\"<>"];
    return [[fileName componentsSeparatedByCharactersInSet:illegalFileNameCharacters] componentsJoinedByString:@""];
}

Credit goes to Peter N Lewis for the idea to use componentsSeparatedByCharactersInSet:
NSString - Convert to pure alphabet only (i.e. remove accents+punctuation)