You should use the static Exists
method on System.IO.File
.
return System.IO.File.Exists("dog.jpg")
Since the method returns a boolean, there is no need for the if
statement in the example you gave.
You can also use a bit of Linq magic to determine if a file exists in a folder structure, like this:
var dir = new System.IO.DirectoryInfo(startFolder);
var fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);
bool fileExists = fileList.Any(f => f.FullName == "dog.jpg");
or even shorter:
return System.IO.Directory
.GetFiles(@"c:\myfolder", "dog.jpg", SearchOption.AllDirectories)
.Any();
which would search the folder specified and all subfolder with the pattern "dog.jpg". The Any()
extension method simply checks whether the IEnumerable
contains any items. I think this is the most efficient way of doing this (based on gut feeling).