Use the File.Exists Function, which returns a Boolean true if the file is found on the disk.
File.Exists. Does a file exist? We can answer this question with File.Exists. File.Exists, part of System.IO, returns a Boolean. It avoids throwing exceptions, so is easy to use.BooleanFile
Example. This program calls File.Exists twice. Please notice first how it imports the System.IO namespace. Around the first File.Exists call, it uses an if-statement. In the second call, it stores the result of File.Exists in a boolean value.
Tip: File.Exists will not throw an exception if the file does not exist. This makes it helpful to call before using other file methods.
So: Using File.Exists is a way to prevent exceptions from other types. StreamReader, for example, will throw if a file is not found.
VB.NET program that uses File.Exists
' See if the file exists in the program directory.
If File.Exists("TextFile1.txt") Then
Console.WriteLine("The file exists.")
' Check a file in the C volume.
Dim exists As Boolean = File.Exists("C:\lost.txt")
The file exists.
Discussion. File.Exists internally accesses the disk. This causes an IO read. Sometimes it is better to simply try to read a file, as with StreamReader. Then catch exceptions if the file is not found. This has fewer steps.
Further, exception handling is faster in many cases than disk reads. In the memory hierarchy, reading from a disk is often much slower than any CPU computation. Therefore, skipping File.Exists and just trying to read files may be better.Locality of Reference
Tip: In some situations, File.Exists is still useful. It may prevent an incorrect state in memory.
Summary. Existence is a complicated subject. File.Exists does not consider this though. It returns True, if a file exists. And it returns False if one does not. It is used within an If-statement conditional, and it may be stored in a Boolean field.