Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fileExistsAtPath returns NO for a directory that exists

fileExistsAtPath is returning NO for a directory that exists. If I have the following code:

NSURL *newDirectoryPath = ... // path does not begin with a tilda
                              // and is created using URLByAppendingPathComponent:isDirectory:

BOOL directoryExists = [self.fileManager fileExistsAtPath:[newDirectoryPath absoluteString]];
if (NO == directoryExists)
{
    BOOL ret = [self.fileManager moveItemAtURL:self.currentPresentationDirectoryPath toURL:newDirectoryPath error: &err];
    // ret is YES, err is nil

    directoryExists = [self.fileManager fileExistsAtPath:[newDirectoryPath absoluteString]];
}

Even though the directory has just been created successfully with moveItemAtURL, fileExistsAtPath is still returning NO.

I know the documentation says this:

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 in the case of file system race conditions.

But I want to understand what the issue is here - if I close the app and relaunch it then the first check for fileExistsAtPath in the code above is still returning NO, even though the directory was previously successfully created during the prior execution of the code, and I can see the directory in the Organizer, and I can also successfully read from the contents of the directory etc. etc.

P.S. is there no fileExistsAtURL: method?

like image 653
Gruntcakes Avatar asked Jan 10 '12 19:01

Gruntcakes


1 Answers

If you have an NSURL, -absoluteURL won't return a usable path for NSFileManager. It will return the absolute URL with the file:// prefix. E.g.: file:///path/to/file.

Instead try to use an other method, like -path. Check if that works.

NSURL *myURL = /* some url */;
NSString *myPath;
BOOL exi;

myPath = [myURL path];
exi = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if(!exi) {
    NSLog(@"File does not exist");
}
like image 118
v1Axvw Avatar answered Oct 11 '22 16:10

v1Axvw