Strange error when moving a folder to temp with moveItemAtPath. Cocoa error 516

Ricardo picture Ricardo · Feb 20, 2012 · Viewed 13.5k times · Source

I try to move a folder with a file to a temp folder, but I always receive the same error: The operation couldn’t be completed. (Cocoa error 516.)

This is the code, do you see anything strange? Thanks in advance.

    // create new folder
NSString* newPath=[[self getDocumentsDirectory] stringByAppendingPathComponent:@"algo_bueno"];
NSLog(@"newPath %@", newPath);
if ([[NSFileManager defaultManager] fileExistsAtPath:newPath]) {
    NSLog(@"newPath already exists.");
} else {
    NSError *error;
    if ([[NSFileManager defaultManager] createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes:nil error:&error]) {
        NSLog(@"newPath created.");
    } else {
        NSLog(@"Unable to create directory: %@", error.localizedDescription);
        return;
    }
}

// create a file in that folder
NSError *error;
NSString* myString=[NSString stringWithFormat:@"Probando..."];
NSString* filePath=[newPath stringByAppendingPathComponent:@"myfile.txt"];
if ([myString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"File created.");
} else {
    NSLog(@"Failed creating file. %@", error.localizedDescription);
    return;
}

// move this folder and its folder
NSString *tmpDir = NSTemporaryDirectory();
NSLog(@"temporary directory, %@", tmpDir);
if ([[NSFileManager defaultManager] moveItemAtPath:newPath toPath:tmpDir error:&error]) {
    NSLog(@"Movido a temp correctamente");
} else {
    NSLog(@"Failed moving to temp. %@", error.localizedDescription);
}

Answer

deanWombourne picture deanWombourne · Feb 20, 2012

Error 516 is NSFileWriteFileExistsError

You can't move a file to a place where a file already exists :)

(See docs here - https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html and search for '516')


More usefully, your destination path should be a file name, not a folder. Try this :

// move this folder and its folder
NSString *tmpDir = NSTemporaryDirectory();
NSString *tmpFileName = [tmpDir stringByAppendingPathComponent:@"my-temp-file-name"];
NSLog(@"temporary directory, %@", tmpDir);
if ([[NSFileManager defaultManager] moveItemAtPath:newPath toPath:tmpFileName error:&error]) {
    NSLog(@"Movido a temp correctamente");
} else {
    NSLog(@"Failed moving to temp. %@", error.localizedDescription);
}