Search code examples
cocoansfilemanager

creating copy of file using file manager is not working for mac app


I have a file in one of the folder in my documents folder .I want to create a copy of that file in some other folder with some other name.The code I am using is

NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent:
    [NSString stringWithFormat:@"Documents/test/test1/%@%@%@",str,currentaudioTobPlayed,@".mp3"]];
NSString * filePath2 = [NSHomeDirectory() stringByAppendingPathComponent:
    [NSString stringWithFormat:@"Documents/test/test1/"]];

NSLog(@"filePat %@",filePath);
NSLog(@"filePath2 %@",filePath2);
NSLog(@"filePath2 %@",fileManager);

[fileManager copyItemAtPath:filePath toPath:filePath2 error:NULL];
[fileManager release];

But this code is not working.Please help!


Solution

  • In:

    NSString * filePath2 = [NSHomeDirectory() stringByAppendingPathComponent:
        [NSString stringWithFormat:@"Documents/test/test1/"]];
    

    you’re not specifying the destination file name: ~/Documents/test/test1 is a directory.

    You could do this instead:

    NSString *sourceName = [NSString stringWithFormat:@"%@%@.mp3",
        str, currentaudioTobPlayed];
    
    // Choose the destination file name
    NSString *destName = [NSString stringWithFormat:@"Copy of %@", sourceName];
    
    NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent:
    [NSString stringWithFormat:@"Documents/test/test1/%@", sourceName]];
    
    NSString * filePath2 = [NSHomeDirectory() stringByAppendingPathComponent:
        [NSString stringWithFormat:@"Documents/test/test1/%@", destName]];
    // Replace Documents/test/test1 with another directory under home,
    // or replace the whole string with an entirely different directory