Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an NSString path (file name) safe

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!

like image 777
cocoafan Avatar asked Aug 15 '09 10:08

cocoafan


3 Answers

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)

like image 74
johnboiles Avatar answered Nov 16 '22 13:11

johnboiles


Unless you're explicitly running the shell or implicitly running the shell by using a function such as popen or system, there's no reason to escape anything but the pathname separator.

You may also want to enforce that the filename does not begin with a full stop (which would cause Finder to hide the file) and probably should also enforce that it is not empty and is fewer than NAME_MAX characters* long.

*syslimits.h says bytes, but if you go through File Manager, it's characters. I'm not sure which is right for Cocoa.

like image 16
Peter Hosey Avatar answered Nov 16 '22 14:11

Peter Hosey


Solution in Swift 4

extension String {
    var sanitizedFileName: String {
        return components(separatedBy: .init(charactersIn: "/\:\?%*|\"<>")).joined()
    }
}

Usage:

"https://myurl.com".sanitizedFileName // = httpsmyurl.com
like image 5
Charlton Provatas Avatar answered Nov 16 '22 12:11

Charlton Provatas