File.Exists
Does a file exist? We can answer this question with File.Exists
in the VB.NET language. File.Exists
, part of System.IO
, returns a Boolean
.
Exists()
avoids throwing exceptions, so is easy to use. We often call the File.Exists
function in an If
-statement in VB.NET programs.
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.
File.Exists
in a boolean value.File.Exists
will not throw an exception if the file does not exist. This makes it helpful to call before using other file methods.File.Exists
is a way to prevent exceptions from other types. StreamReader
, for example, will throw if a file is not found.Imports System.IO Module Module1 Sub Main() ' See if the file exists in the program directory. If File.Exists("TextFile1.txt") Then Console.WriteLine("The file exists.") End If ' Check a file in the C volume. Dim exists As Boolean = File.Exists("C:\lost.txt") Console.WriteLine(exists) End Sub End ModuleThe file exists. False
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
.
File.Exists
and just trying to read files may be better.File.Exists
is still useful. It may prevent an incorrect state in memory.File.Exists
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.