迅捷:使用"/"在文件名中使用createDirectoryAtPath进行斜杠 [英] Swift: Using "/" slash in filename with createDirectoryAtPath
问题描述
我有一个名为我的项目"的文件夹.当我尝试调用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
这是我的代码:
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
{
}
}
我也尝试过:
projectName.stringByReplacingOccurrencesOfString("/", withString: "\:")
匹配终端,但是Xcode抱怨无效的转义序列.
to match the terminal but Xcode complains about an invalid escape sequence.
更新1:对文件夹名称进行编码也无法正常工作.
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.
但是,OS X Finder允许使用带斜杠的文件名,并且可以使用 通过在显示的文件名的斜杠"/"和文件系统中的冒号:"之间进行翻译. (因此,您不能使用冒号 Finder中的文件名.)
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.)
因此,"My/Project"文件夹在文件系统中存储为"My:Project",并且应使用 unscaped 冒号":"
替换文件名中的"/"
.
解决您的问题.
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.)
这篇关于迅捷:使用"/"在文件名中使用createDirectoryAtPath进行斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!