How to check if a file exists in Documents folder?

151,528

Solution 1

Swift 3:

let documentsURL = try! FileManager().url(for: .documentDirectory,
                                          in: .userDomainMask,
                                          appropriateFor: nil,
                                          create: true)

... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:

let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)

Objective-C:

NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

Solution 2

Apple recommends against relying on the fileExistAtPath: method. It's often better to just try to open a file and deal with the error if the file does not exist.

NSFileManager Class Reference

Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.

Source: Apple Developer API Reference

From the secure coding guide.

To prevent this, programs often check to make sure a temporary file with a specific name does not already exist in the target directory. If such a file exists, the application deletes it or chooses a new name for the temporary file to avoid conflict. If the file does not exist, the application opens the file for writing, because the system routine that opens a file for writing automatically creates a new file if none exists. An attacker, by continuously running a program that creates a new temporary file with the appropriate name, can (with a little persistence and some luck) create the file in the gap between when the application checked to make sure the temporary file didn’t exist and when it opens it for writing. The application then opens the attacker’s file and writes to it (remember, the system routine opens an existing file if there is one, and creates a new file only if there is no existing file). The attacker’s file might have different access permissions than the application’s temporary file, so the attacker can then read the contents. Alternatively, the attacker might have the file already open. The attacker could replace the file with a hard link or symbolic link to some other file (either one owned by the attacker or an existing system file). For example, the attacker could replace the file with a symbolic link to the system password file, so that after the attack, the system passwords have been corrupted to the point that no one, including the system administrator, can log in.

Solution 3

If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking

for (int i = 0; i < numberHere; ++i){
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
    NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
    if (fileExists == NO){
        cout << "DOESNT Exist!" << endl;
    } else {
        cout << "DOES Exist!" << endl;
    }
}

Solution 4

Swift 2.0

This is how to check if the file exists using Swift

func isFileExistsInDirectory() -> Bool {
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentsDirectory: AnyObject = paths[0]
    let dataPath = documentsDirectory.stringByAppendingPathComponent("/YourFileName")

    return NSFileManager.defaultManager().fileExistsAtPath(dataPath)
}

Solution 5

check if file exist in side the document/catchimage path :

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
    // ur code here
} else {
    // ur code here** 
}
Share:
151,528

Related videos on Youtube

Obliviux
Author by

Obliviux

Updated on May 21, 2020

Comments

  • Obliviux
    Obliviux almost 4 years

    I have an application with In-App Purchase, that when the user buy something, download one html file into the Documents folder of my app.

    Now I must check if this HTML file exists, so if true, load this HTML file, else load my default html page.

    How I can do that? With NSFileManager I can't get outside of mainBundle..

    • Admin
      Admin almost 11 years
      "With NSFileManager i can't get outside of mainBundle" - from where did you get this piece of misinformation?
  • Epsilon Prime
    Epsilon Prime over 14 years
    Note that you're loading a file out of your application's personal Documents directory, not the global one you find if you're jailbroken. If you install your application in /Applications as if it was a main application you'll have access to the entire file system and you'll use the shared Documents directory. If you install it via iTunes or XCode you'll be using your applications' personal directory. It's nice to store files in your local directory for backup purposes.
  • Govind
    Govind over 10 years
    objectAtIndex:0 can be now replaced with firstObject
  • temporary_user_name
    temporary_user_name over 9 years
    Or just [0] via index accessing
  • Itachi
    Itachi almost 8 years
    firstObject is more safe than [0] and objectAtIndex:0
  • Nikolai Ruhe
    Nikolai Ruhe almost 8 years
    @Itachi Actually in this case I prefer the exception when there is no object in the array. If the result of firstObject is nil there's no sensible way how the program could continue, as something in the Apple frameworks is seriously broken.
  • SnareChops
    SnareChops almost 6 years
    While this is an good answer on it's own providing great advice. It would be good to see how this could be implemented with a small code example.