2011-04-26 36 views
11

我想使用copyItemAtPath複製目錄,但每次失敗時都會出現「操作無法完成。文件存在」錯誤。copyItemAtPath總是失敗,並存在文件存在錯誤

下面是我使用的日誌

NSLog(@"Copying from: %@ to: %@", [[NSUserDefaults standardUserDefaults] objectForKey:@"template_1_path"], path); 
if(![file_manager copyItemAtPath:[NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"template_1_path"]] toPath:[NSString stringWithFormat:@"%@", path] error:&error]) { 
     NSLog(@"%@" [error localizedDescription]); 
} 

示例代碼 -

"Copying from: /Users/testuser/Sites/example_site to: /Users/testuser/Desktop" 
"The operation couldn’t be completed. File exists" 

什麼我做錯了任何想法?

在此先感謝!

回答

21

您似乎試圖將文件「/ Users/testuser/Sites/example_site」複製到文件「/ Users/testuser/Desktop/example_site」中,假設您可以指定目標目錄並且它將使用源文件名。這不起作用。 Quoth the documentation

當文件被複制時,目標路徑必須以文件名結尾 - 源文件名沒有隱式採用。

+0

這對於moveItemAtPath也是如此:...和moveItemAtURL:... – LaborEtArs 2016-05-13 13:34:10

16

您正在嘗試複製具有相同文件名的內容。嘗試這樣的:

- (BOOL)copyFolderAtPath:(NSString *)sourceFolder toDestinationFolderAtPath:(NSString*)destinationFolder { 
    //including root folder. 
    //Just remove it if you just want to copy the contents of the source folder. 
    destinationFolder = [destinationFolder stringByAppendingPathComponent:[sourceFolder lastPathComponent]]; 

    NSFileManager * fileManager = [ NSFileManager defaultManager]; 
    NSError * error = nil; 
    //check if destinationFolder exists 
    if ([ fileManager fileExistsAtPath:destinationFolder]) 
    { 
     //removing destination, so soucer may be copied 
     if (![fileManager removeItemAtPath:destinationFolder error:&error]) 
     { 
      NSLog(@"Could not remove old files. Error:%@",error); 
      [error release]; 
      return NO; 
     } 
    } 
    error = nil; 
    //copying destination 
    if (!([ fileManager copyItemAtPath:sourceFolder toPath:destinationFolder error:&error ])) 
    { 
     NSLog(@"Could not copy report at path %@ to path %@. error %@",sourceFolder, destinationFolder, error); 
     [error release]; 
     return NO; 
    } 
    return YES; 
} 
相關問題