开发者

How to test for valid file name in Mac OS X

Anyone know how to test if a string is a valid file name in Mac OS X, other than trying to create file with that name?

The issue I'm having is that sometimes, a file name can be too large. OSX has a byte limit for filenames and with unicode characters you can't ju开发者_运维问答st check the length of the string since they can be more than 1 byte.


On a Mac OS X, a file is nothing more than a resource; and the path/filename is the location. Create an NSURL object using + (id)fileURLWithPath:(NSString *)path. The method will only return a valid object if the filename is valid.

Excerpt from Apple Docs:

  • NSURL objects can be used to refer to files, and are the preferred way to do so.
  • The NSURL class will fail to create a new NSURL object if the path being passed is not well-formed—the path must comply with RFC 2396.


Use NSFileManager.

-- Updated:

Try this:

if([testPath compare: [NSString stringWithUTF8String:[testPath fileSystemRepresentation]]] == NSOrderedSame) {
    //testPath is a valid Path
}

No guarantees on what it will do though.


I think the only invalid character (except control chars) on OSX is the colon - so you simply have to test if the new filename contains colons.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜