Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Using "/" slash in filename with createDirectoryAtPath

Tags:

path

swift

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?

like image 496
iphaaw Avatar asked Dec 19 '22 18:12

iphaaw


1 Answers

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.)

like image 105
Martin R Avatar answered Dec 26 '22 16:12

Martin R