Swift: Using "/" slash in filename with createDirectoryAtPath

Viewed 1936

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?

1 Answers
Related