Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copyItemAtPath always fails with File exists error

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!

like image 366
Raphael Caixeta Avatar asked Apr 26 '11 02:04

Raphael Caixeta


2 Answers

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.

like image 157
Anomie Avatar answered Oct 21 '22 16:10

Anomie


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;
}
like image 17
Leandro Avatar answered Oct 21 '22 16:10

Leandro