I have a folder called "My / Project". When I try to call createDirectoryAtPath I get two folders created "My " with a subfolder of " Project".
I have looked at how the terminal represents this:
/Users/currentuser/Documents/Projects/My\ \:\ Project
Here is my code:
let projectName = "My / Project"
let path:NSString = "/Users/currentuser/Documents/Projects/"
let fullPath:NSString = path.stringByAppendingPathComponent(projectName)
if (!NSFileManager.defaultManager().fileExistsAtPath(fullPath:NSString))
{
do
{
try NSFileManager.defaultManager().createDirectoryAtPath(fullPath:NSString, withIntermediateDirectories: true, attributes: nil)
}
catch
{
}
}
I have also tried :
projectName.stringByReplacingOccurrencesOfString("/", withString: "\:")
to match the terminal but Xcode complains about an invalid escape sequence.
Update #1: Encoding the folder name also failed to work.
let encodedPath = projectName.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLUserAllowedCharacterSet())
let fullPath2:NSString = path.stringByAppendingPathComponent(encodedPath!)
NSFileManager.defaultManager().fileExistsAtPath(encodedPath!)
What is the best way of doing this?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With