Nubaslon
Nubaslon

Reputation: 751

How to rename files from Documents directory?

I am saving my files in Document directory named 1.png, 2.png, 3.png, 4.png, 5.png. If I delete the original file 3.png, how do I rename files 4.png and 5.png to be called 3.png and 4.png respectively?

This is the code I am using to write the files in the first place:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[appDel.photo addObject:@"photo"];
NSString *imageName = [NSString stringWithFormat:@"%i.png", [appDel.photo count]];
appDel.numberPhoto = [appDel.photo count];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
                  imageName];
NSData* data = UIImagePNGRepresentation(image); 
[data writeToFile:path atomically:YES];

Upvotes: 4

Views: 9210

Answers (1)

B.S.
B.S.

Reputation: 21726

To get NSDocuments directory use :

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];

How to rename file you can find here:

How to rename a file using NSFileManager

If you do not know the names of the files in documents directory you can use :

NSArray *directoryContent = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];

This array contains all filenames you need. So you can rename them all.

Upvotes: 2

Related Questions