Depends on your program flow and the actions you're performing. If you expect the file to exist, you can rely on exception handling, since your program cannot continue if it doesn't and the exception most probably needs to be handled higher up in the call chain.
Otherwise, you'll get the True|False|FileNotFound
return code madness, if the method in question is something like ReadFile()
.
Using File.Exists to "safely" open a file is pretty useless. Consider this:
public String ReadFile(String filename)
{
if (!File.Exists(filename))
{
// now what? throw new FileNotFoundException()? return null?
}
// Will throw FileNotFoundException if not exists, can happen (race condition, file gets deleted after the `if` above)
using (var reader = new StreamReader(filename))
{
return reader.ReadToEnd();
}
}
One could say you'd want to check if a file exists if you want to append data to it, but the StreamWriter constructor has an overload with an append
parameter, which will let the writer create the file if it doesn't exist and append to it if it does.
So, perhaps the question could better be: what valid use cases exist for File.Exists
? And luckily that question has already been asked and answered.