I guess that you are referring to this pattern:
// A
if (File.Exists(myFilename))
{
// B
// Do something which assumes that myFilename definitely exists
}
The problem here is that on a platform which has pre-emptive multi-tasking (such as Windows), there is nothing to stop some other process deleting myFilename
between the places I have marked A
and B
.
As a result, file access code should always be defensive - that is, be prepared to handle FileNotFoundException
, UnauthorizedAccessException
, and indeed all the other exceptions that can occur during IO operations (see eg the docs for File.ReadAllText
).
This is not to deny the usefulness of using File.Exists
as an additional earlier check - if, say, the user has entered a filename manually, a sanity check that it exists will catch typos - but this can never be the last check.