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!
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.
You are trying to copy something with the same file name. Try something like this:
- (BOOL)copyFolderAtPath:(NSString *)sourceFolder toDestinationFolderAtPath:(NSString*)destinationFolder {
//including root folder.
//Just remove it if you just want to copy the contents of the source folder.
destinationFolder = [destinationFolder stringByAppendingPathComponent:[sourceFolder lastPathComponent]];
NSFileManager * fileManager = [ NSFileManager defaultManager];
NSError * error = nil;
//check if destinationFolder exists
if ([ fileManager fileExistsAtPath:destinationFolder])
{
//removing destination, so soucer may be copied
if (![fileManager removeItemAtPath:destinationFolder error:&error])
{
NSLog(@"Could not remove old files. Error:%@",error);
[error release];
return NO;
}
}
error = nil;
//copying destination
if ( !( [ fileManager copyItemAtPath:sourceFolder toPath:destinationFolder error:&error ]) )
{
NSLog(@"Could not copy report at path %@ to path %@. error %@",sourceFolder, destinationFolder, error);
[error release];
return NO;
}
return YES;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With