Piyush Dubey
Piyush Dubey

Reputation: 2414

Rename the folder of document directory

This could be easy, but I am not getting the problem.
I am using below code to rename the folders of document directory and is working fine except one case.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"Photos"];
    NSArray * arrAllItems = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dataPath error:NULL]; // List of all items
    NSString *filePath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [arrAllItems objectAtIndex:tagSelected]]];

    NSString *newDirectoryName = txtAlbumName.text; // Name entered by user
    NSString *oldPath = filePath;
    NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newDirectoryName];
    NSError *error = nil;
    [[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:&error];
    if (error) {
        NSLog(@"%@",error.localizedDescription);
        // handle error
    }


Now, my problem is if there is a folder named "A"(capital letter A) and I am renaming it to "a" (small letter a), then it is not working and giving an error.
I am not getting where the problem is.

Upvotes: 2

Views: 638

Answers (1)

Martin R
Martin R

Reputation: 539795

The HFS+ file system (on OS X) is case insensitive, but case preserving. That means if you create a folder "A" and then check if there is a folder "a", you will get "yes" as an answer.

The file manager moveItemAtPath:toPath:... checks first if the destination path already exists and therefore fails with

NSUnderlyingError=0x7126dc0 "The operation couldn’t be completed. File exists"

One workaround would be to rename the directory to some completely different name first:

A --> temporary name --> a

But a much easier solution is to use the BSD rename() system call, because that can rename "A" to "a" without problem:

if (rename([oldPath fileSystemRepresentation], [newPath fileSystemRepresentation]) == -1) {
    NSLog(@"%s",strerror(errno));
}

Note that the problem occurs only on the iOS Simulator, not on the device, because the device file system is case sensitive.

Swift:

let result = oldURL.withUnsafeFileSystemRepresentation { oldPath in
    newURL.withUnsafeFileSystemRepresentation { newPath in
        rename(oldPath, newPath)
    }
}
if result != 0 {
    NSLog("%s", strerror(errno))
}

Upvotes: 4

Related Questions