Mugen
Mugen

Reputation: 9095

Broken symlink file throws FileNotFoundException but passes File.Exists

I have a broken symbolic link:

lrwxr-xr-x    1 mugen  staff     10 Nov  5  2018 README.md -> README.md?

A check of File.Exists(filePath) returns true, but calling new FileStream(filePath, FileMode.Open) throws System.IO.FileNotFoundException.

What is the best strategy to avoid trying to open this file?

Upvotes: 1

Views: 424

Answers (1)

Mureinik
Mureinik

Reputation: 312086

This behavior kind of makes sense - the file (symbolic link) exists, but you can't read it because it points to a file that doesn't exist (broken symbolic link).

Personally, I'm not a big fan of these pre-checks. First, they are racy by nature - even if all the checks pass, something can happen on the file system after that and before you try using the file (admittedly, it's less of an issue in a local filesystem, but I still think it's a bad practice). Second, it's expensive - all these checks perform at least some I/O, and often redundantly so (since you'll perform the same I/O again when you open the file).

I'd just attempt to open the file, and catch the exception:

FileStream fs = null;
try {
    fs = new FileStream(filePath, FileMode.Open);
    // Use fs
} catch (IOException e) {
    // Handle the exception in some elegant way
} finally {
    if (fs != null) {
        fs.Close();
    }
}

Upvotes: 2

Related Questions