Swift: Using "/" Slash in Filename with Createdirectoryatpath

Swift: Using / slash in filename with createDirectoryAtPath

The slash is the path delimiter in the file system, and not allowed
in file name components.

The OS X Finder however allows file names with a slash, and that works
by translating between the slash "/" for displayed file names and the colon ":" in the file system. (As a consequence, you cannot use the colon
for file names in the Finder.)

The folder "My / Project" is therefore stored in the file system as "My : Project", and replacing "/" in the file name with an unescaped colon ":" should
solve your problem.

(The colon has a special meaning in the shell, and that is why you see
\: in the Terminal.)

How to encode a file NSURL to point to a file with a '/' in the name

/ is not actually a legal character in Darwin (OS X or iOS) file names. The UI just makes it look like it is in some cases. OS X exchanges : for /. So the actual name of your file is This:That. Depending on what tool you're using it will be rendered as either This:That or This/That. This is an old holdover from Mac OS 9. In Mac OS 9 and earlier, : is illegal, but / is legal. In Darwin (via OS X), the opposite is true.

You really, really want to avoid this situation if you can, and just not have / or : in your filenames (- and _ are generally safer, and . is often fine). But if you must, then you're going to have to swap it for : in your string.

Converting URL to String and back again

fileURLWithPath() is used to convert a plain file path (e.g. "/path/to/file") to an URL. Your urlString is a full URL string including the scheme, so you should use

let url = NSURL(string: urlstring)

to convert it back to NSURL. Example:

let urlstring = "file:///Users/Me/Desktop/Doc.txt"
let url = NSURL(string: urlstring)
println("the url = \(url!)")
// the url = file:///Users/Me/Desktop/Doc.txt


Related Topics



Leave a reply



Submit