【问题标题】:copyItemAtPath always fails with File exists errorcopyItemAtPath 总是因文件存在错误而失败
【发布时间】:2011-08-12 17:07:26
【问题描述】:

我正在尝试使用 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"

关于我做错了什么有什么想法吗?

提前致谢!

【问题讨论】:

    标签: objective-c cocoa nsfilemanager


    【解决方案1】:

    您似乎正在尝试将文件“/Users/testuser/Sites/example_site”复制到文件“/Users/testuser/Desktop/example_site”,假设您只需指定目标目录并且它将使用源文件名。这不起作用。阔思the documentation

    在复制文件时,目标路径必须以文件名结尾——没有隐式采用源文件名。

    【讨论】:

      【解决方案2】:

      您正在尝试复制具有相同文件名的内容。试试这样的:

      - (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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多