copyItemAtPath always fails with File exists error

Raphael Caixeta picture Raphael Caixeta · Apr 26, 2011 · Viewed 14.7k times · Source

I'm trying to copy directories with copyItemAtPath, yet every time it fails with a "The operation couldn’t be completed. File exists" error.

Here's the code I'm using

NSLog(@"Copying from: %@ to: %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"template_1_path"], path);
if(![file_manager copyItemAtPath:[NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"template_1_path"]] toPath:[NSString stringWithFormat:@"%@", path] error:&error]) {
      NSLog(@"%@" [error localizedDescription]);
}

Example of the log -

"Copying from: /Users/testuser/Sites/example_site to: /Users/testuser/Desktop"
"The operation couldn’t be completed. File exists"

Any ideas on what I'm doing wrong?

Thanks in advance!

Answer

Anomie picture Anomie · Apr 26, 2011

You seem to be trying to copy the file "/Users/testuser/Sites/example_site" to the file "/Users/testuser/Desktop/example_site", assuming that you can just specify the destination directory and it will use the source filename. This does not work. 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.