Search code examples
iosobjective-cnsfilemanager

Renaming all files and directories in NSLibraryDirectory


How can I rename all files and directories to lower case in NSLibraryDirectory\myFolder?

I found that I can to use:

[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:[oldPath lowercaseString] error:&error];

to renaming directories.

NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:path error:nil];

To getting array with directory contents but how I can check if directoryContent[0] is directory or file.


Solution

  • You could use this to check if a NSUrl is a directory or file:

    for (NSURL *item in directoryContent) {
        NSString *path = [item path];
        BOOL isDir;
        if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
            if (isDir) {
                NSLog(@"%@ is a directory", path);
            } else {
                NSLog(@"%@ is a file", path);
            }
        } else {
            NSLog(@"%@ does not exist", path);
        }
    }
    

    UPDATE:

    To rename all contents of your directory you could use this:

    NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:path error:nil];
    BOOL isDir;
    for (NSURL *item in directoryContent) {
    
        if ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) {
            if (isDir) {
                // create a new directory with lowercase name,
                // move contents of old directory to the new one
                // then delete the old directory
            } else {
                [[NSFileManager defaultManager] moveItemAtPath:path toPath:[path lowercaseString] error:&error];
            }
        }
    }