2012-07-25 106 views
0

我遇到问题,我需要将Documents子目录的内容移动到Documents Directory的“根目录”。 为此,我想将子目录的所有内容复制到Documents目录,然后删除我的子目录。将目录的内容复制到Documents目录

NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:@"inbox"] 

这就是我如何获取Documents目录的路径以及我的子目录名为inbox的路径。

NSArray *inboxContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentinbox error:nil]; 
NSFileManager *fileManager = [NSFileManager defaultManager]; 

然后我创建一个包含子文件夹中所有文档的数组,并初始化文件管理器。

现在我必须执行for循环,为每个文档将文档从子目录复制到文档目录。

for(int i=0;i<[inboxContents count];i++){ 
    //here there is the problem, I don't know how to copy each file 

我想使用moveItemAtPath方法,但我不知道如何获取每个文件的路径。

希望您能理解我的问题, 感谢您的帮助 NICCO

+0

moveItemAtPath不起作用,因为您无法从应用程序包目录中删除文件。 – 2012-07-25 16:43:47

+0

@ H2CO3文件目录不是捆绑包的一部分。 – Joe 2012-07-25 16:49:36

+0

@Joe对不起,对不起,我误解了这个问题,出现的通常问题是无法写入XXXX.app(它是*本身的包)。 – 2012-07-25 16:51:34

回答

2

您可以使用moveItemAtPath:toPath:error:如下。

NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *documentinbox = [documentsDirectory stringByAppendingPathComponent:@"inbox"]; 

//Initialize fileManager first 
NSFileManager *fileManager = [NSFileManager defaultManager]; 

//You should always check for errors 
NSError *error; 
NSArray *inboxContents = [fileManager contentsOfDirectoryAtPath:documentinbox error:&error]; 
//TODO: error handling if inboxContents is nil 

for(NSString *source in inboxContents) 
{ 
    //Create the path for the destination by appending the file name 
    NSString *dest = [documentsDirectory stringByAppendingPathComponent: 
         [source lastPathComponent]]; 

    if(![fileManager moveItemAtPath:source 
          toPath:dest 
          error:&error]) 
    { 
     //TODO: Handle error 
     NSLog(@"Error: %@", error); 
    } 
} 
相关问题