How can I know if a filename is valid in objective c? I can't find anything in NSString "Working with Paths" tasks and I don't think doing a manual regex is the right way.
Asked
Active
Viewed 989 times
1
-
Surely any string is a valid file name - HFS+ uses Unicode – mmmmmm Jun 16 '11 at 12:11
-
Even aaa/aaa? that will be considered a directory – Daniel Jun 16 '11 at 12:11
-
@Mark: I see I can rename a file to it on my mac, but how can I save a file named `aaa/aaa`? it will try to save file named `aaa` in a folder named `aaa`. Even using `stringByAppendingPathComponent` keeps it as-is. – Daniel Jun 16 '11 at 12:15
-
Which if you have folder aaa will work - so you can't tell just from the string – mmmmmm Jun 16 '11 at 12:19
-
This answer worked for me: http://stackoverflow.com/questions/1281576/how-to-make-an-nsstring-path-file-name-safe – wfbarksdale Jul 19 '13 at 13:40
1 Answers
2
It's actually pretty difficult to know if a filename is valid. The best thing to do is try the operation you want to do with it and handle the errors. For instance, if you want to read a file, open it for reading. If the file is not valid for doing that, the open will fail.
Edit
If you want to limit users to selecting paths in the current directory, you can do this:
NSArray* pathComponents = [string pathComponents];
if ([pathComponents count] != 1)
{
// error
}

JeremyP
- 84,577
- 15
- 123
- 161
-
I want my users to enter a file name. if they enter something like `../../../../veryDangerusFile` I don't want the program to run loose. I want it to not allow directory changes at all. – Daniel Jun 16 '11 at 15:27
-
Why not just if ([string rangeOfString:@"/"].location != NSNotFound) { // error }..? The array splitting just to see if a / exists seems redundant. – Kalle Sep 02 '12 at 09:49
-
@Kalle: I don't like explicitly assuming the path separator is a `/`. It's better to use the proper file system path manipulation code. – JeremyP Sep 05 '12 at 09:49
-
I guess if you're writing multi platform code that makes sense, yeah. (I'm not.) – Kalle Sep 05 '12 at 11:19