Search code examples
objective-ccocoansfilemanagerfile-management

Rename file in Cocoa?


How would I rename a file, keeping the file in the same directory?

I have a string containing a full path to a file, and a string containing a the new filename (and no path), for example:

NSString *old_filepath = @"/Volumes/blah/myfilewithrubbishname.avi";
NSString *new_filename = @"My Correctly Named File.avi";

I know about NSFileManager's movePath:toPath:handler: method, but I cannot workout how to construct the new file's path..

Basically I'm looking for the equivalent to the following Python code:

>>> import os
>>> old_filepath = "/Volumes/blah/myfilewithrubbishname.avi"
>>> new_filename = "My Correctly Named File.avi"
>>> dirname = os.path.split(old_filepath)[0]
>>> new_filepath = os.path.join(dirname, new_filename)
>>> print new_filepath
/Volumes/blah/My Correctly Named File.avi
>>> os.rename(old_filepath, new_filepath)

Solution

  • NSFileManager and NSWorkspace both have file manipulation methods, but NSFileManager's - (BOOL)movePath:(NSString *)source toPath:(NSString *)destination handler:(id)handler is probably your best bet. Use NSString's path manipulation methods to get the file and folder names right. For example,

    NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFilename];
    [[NSFileManager defaultManager] movePath:oldPath toPath:newPath handler:nil];
    

    Both classes are explained pretty well in the docs, but leave a comment if there's anything you don't understand.