How to copy a file to portable drive root with cocoa?

陌路散爱 提交于 2019-12-13 17:35:06

问题


I've tried the following

[[NSFileManager defaultManager] copyItemAtPath:@"whatever.txt"
 toPath:@"/Volumes/MyDrive" error:&copyError];

This gives me the error "The operation couldn’t be completed. File exists"

If I try to copy it to "/Volumes/MyDrive/testFolder" everything copies to testFolder just fine.


回答1:


I've tried the following

[[NSFileManager defaultManager] copyItemAtPath:@"whatever.txt"
 toPath:@"/Volumes/MyDrive" error:&copyError];

This gives me the error "The operation couldn’t be completed. File exists"

First, as KennyTM already told you, the error message is telling you one possible cause of the problem: The file already exists. The destination must not exist; you must either delete it or give a different name for the destination.

Second, there is another possible cause of the problem: You only specified the destination folder, not the complete destination path. You must specify the complete destination path, including the destination filename. Quoth the documentation:

“When a file is being copied, the destination path must end in a filename—there is no implicit adoption of the source filename.”

If you want the copy to have the pathname /Volumes/MyDrive/whatever.txt, that's the pathname you need to pass.

Also, don't forget to check whether the copy succeeded before you attempt to look at the error object. You should only look at the error object if the copy failed.

If I try to copy it to "/Volumes/MyDrive/testFolder" everything copies to testFolder just fine.

I think you'll find that testFolder is, in fact, a file—specifically, it's the copy of whatever.txt.




回答2:


Isn't the error very clear? "The operation couldn’t be completed. File exists". The doc of -copyItemAtPath:… states that:

The file specified in srcPath must exist, while dstPath must not exist prior to the operation.

You need to call -removeItemAtPath:error: to remove the destination file if you want to override it.



来源:https://stackoverflow.com/questions/3639404/how-to-copy-a-file-to-portable-drive-root-with-cocoa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!