iOS copy directories including subdirectories

12,027

Solution 1

You can use the same NSFileManager methods that you know and love for directories as well. For example:

if ([[NSFileManager defaultManager] fileExistsAtPath:pathToTempDirectoryInMain]) {
    [[NSFileManager defaultManager] removeItemAtPath:pathToTempDirectoryInMain error:nil];
}
NSError *copyError = nil;
if (![[NSFileManager defaultManager] copyItemAtPath:pathToTempDirectory toPath:pathToTempDirectoryInMain error:&copyError]) {
    NSLog(@"Error copying files: %@", [copyError localizedDescription]);
}

Solution 2

The NSFileManager methods removeItemAtPath:error:, removeItemAtURL:error:, copyItemAtPath:toPath:error:, and copyItemAtURL:toURL:error: methods handle directories.

You might also look at moveItemAtPath:toPath:error: and moveItemAtURL:toURL:error:.

Share:
12,027

Related videos on Youtube

Jaume
Author by

Jaume

Updated on June 07, 2022

Comments

  • Jaume
    Jaume almost 2 years

    I am working with iOS document folder called "temp" that allocates subdirectories that contain files dowloaded from remote url. Now I need to copy "temp" directory and all its contents to "main" folder (overwrite existing that was previously created). I know how to handle files but how to copy whole directory? Thank you

  • Alix
    Alix over 8 years
    I used copyItemAtPath method of file manager. Yes it did copy files but it left all the directory at that level. I want everything to be copied in the dir structure. Any pointers ?
  • Volomike
    Volomike about 8 years
    By the way on this, because it might not be readily apparent, you need user permissions on the process that runs this.
  • Volomike
    Volomike about 8 years
    @Alix Whether I run copyItemAtPath or moveItemAtPath, it creates a directory by the pathname you specify if it does not exist. So, if I created /tmp/src and then wanted to copy into /tmp/dest, or move it into /tmp/dest, if I run jrtc27's solution, it will automatically delete any previous /tmp/dest and then copy it into /tmp/dest. As another example, let's say I have /tmp/Alix and a folder like /home/alix/Documents and I want to put an Alix folder in there. Fine -- I just set source to /tmp/Alix and dest. to /home/alix/Documents/Alix. It will automatically create the Alix folder for you.
  • matm
    matm almost 4 years
    While this answers part of the question, it omits the other part where existing contents of target directory (that is not present in source) is to be preserved.
  • jrtc27
    jrtc27 over 3 years
    Sure, if that's what you want then you need to be more clever. But that's not what was asked ("Now I need to copy "temp" directory and all its contents to "main" folder (overwrite existing that was previously created)"), as also evidenced by this being the accepted answer.