VB.NET File.Exists: Get BooleanUse the File.Exists Function, which returns a Boolean true if the file is found on the disk.
Does a file exist? And does it matter whether it exists or not? We can answer the first question with File.Exists. The second question depends on the program context. File.Exists, part of System.IO, returns a Boolean.BooleanFile
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.StreamReader
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.
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.Memory Hierarchy
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.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.