Depends on the flow of your program and the actions you perform. If you expect the file to exist, you can rely on exception handling, since your program cannot continue if it is not, and the exception will most likely need to be handled higher in the call chain.
Otherwise, you will get True|False|FileNotFound code return madness if the method in question is similar to 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(); } }
We can say that you want to check if the file exists if you want to add data to it, but the StreamWriter constructor is overloaded with the append parameter, which will allow the author to create the file if it does not exist and is added to it if it does.
So, perhaps the question might be better: what are the valid use cases for File.Exists ? And, fortunately, this question has already been asked and answered .
source share