I have some code that copies all the directories from “/Documents” to “Library/Caches/”. The code is as follows:
NSString *oldPath = [NSString stringWithFormat:@"%@/Documents/", NSHomeDirectory()];
NSString *newPath = [NSMutableString stringWithFormat:@"%@/Library/Caches/", NSHomeDirectory()];
NSError *error = nil;
// get the list of all files and directories
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileList = [fileManager contentsOfDirectoryAtPath:oldPath error:&error];
if(error != nil)
{
NSLog(@"\n\n\n1. There was an error in the file operation: %@", [error localizedDescription]);
return;
}
for(NSString *file in fileList)
{
NSString *path = [oldPath stringByAppendingPathComponent:file];
NSLog(@"The path for the file is: %@", path);
BOOL isDir = NO;
BOOL dirExists = [fileManager fileExistsAtPath:path isDirectory:(&isDir)];
if(isDir && dirExists)
{
//Move to the new location
[fileManager copyItemAtPath:path toPath:[newPath stringByAppendingPathComponent:file] error:&error];
if(error != nil)
{
NSLog(@"\n\n\n2. There was an error in the file operation: %@", [error localizedDescription]);
}
else
{
[fileManager removeItemAtPath:path error:&error];
if(error != nil)
NSLog(@"\n\n\n3. There was an error in the file operation: %@", [error localizedDescription]);
}
}
}
The copy works fine. I can see all the directories copied to the new location.
The problem is that the empty directories still remain in the Documents folder. I read up on removeItemAtPath in the docs and it says there that the contents of the directory are deleted. Whether the actual directory itself is deleted or not has no mention.
Could someone tell me what could be going wrong in the code? Why do the empty directories still remain?
EDIT:
On the first pass, when the directories exist in Documents, but not in Library/Caches, removeItemAtPath does not throw an error. The empty directories still remain in Documents, though. On the second pass of the above code, it attempts to remove the empty directories and removeItemAtPath throws a cocoa error 516 which is basically file not found – this is weird, because I can still see those empty directories.
Also, I’m running this code on iPhone Simulator 4.3.2 and iPhone Simulator 5.0, and monitoring the directory structure on my Mac in /Users/Library/Application Support/iPhone Simulator/….
This may be happening because of the trailing “/” in “/Documents/”. Try removing the trailing “/” from the first 2 lines, or use this: