开发者

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 standardUserDefault开发者_如何学Cs] 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜