Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

path - Swift: Using "/" slash in filename with createDirectoryAtPath

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...