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
How to Implement iOS 11's Mkusertrackingbutton
Swift Task Continuation Misuse: Leaked Its Continuation - for Delegate
How to Restrict a Protocol to Value Types Only
Generatesdecimalnumbers for Numberformatter Does Not Work
If the Swift 'Guard' Statement Must Exit Scope, What Is the Definition of Scope
System Volume Change Observer Not Working on iOS 15
Programmatically Disabling Screenshot in App
When Does the Copying Take Place for Swift Value Types
How to Deallocate Realitykit Arview()
Scenekit - Custom Geometry Does Not Show Up
Create View Based Nstableview Programmatically Using Bindings in Swift
Why Does Swiftui Uihostingcontroller Have Extra Spacing
Extend Generic Array<T> to Adopt Protocol
Spritekit and Scenekit - How to Completely Pause a Game
Swift Encode Tuple Using Nscoding