Q:

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?

A:

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 */
}

A:

if ([[NSFileManager defaultManager] fileExistsAtPath:myFilePath])

A:

NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"file name"];

if([fileManager fileExistsAtPath:writablePath]){ 
// file exist
}
else{ 
    // file doesn't exist
}

