Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file name exists in document directory

In my application I am using the following code to save images/files into the application’s document directory:

-(void)saveImageDetailsToAppBundle{
    NSData *imageData = UIImagePNGRepresentation(userSavedImage); //convert image into .png format.
    NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
    NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png",txtImageName.text]]; //add our image to the path

    NSLog(fullPath);

    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the image

    NSLog(@"image saved"); 
}

However, there is a problem with the image name. If a file exists in the documents directory, the new file with the same name will overwrite the old file. How can I check if the file name exists in the documents directory?

like image 363
Vipin Avatar asked Jun 27 '11 10:06

Vipin


1 Answers

Use NSFileManager's fileExistsAtPath: method to check if it exists or not.

usage

if ( ![fileManager fileExistsAtPath:filePath] ) {
    /* File doesn't exist. Save the image at the path */
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; 
} else {
    /* File exists at path. Resolve and save */
}
like image 187
Deepak Danduprolu Avatar answered Sep 19 '22 13:09

Deepak Danduprolu