File.Exists Function
This page was last reviewed on Mar 29, 2022.
Dot Net Perls
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.
Function info. Exists() avoids throwing exceptions, so is easy to use. We often call the File.Exists function in an If-statement in VB.NET programs.
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.
And 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.
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 Module
The file exists. False
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 We could catch exceptions if the file is not found. This has fewer steps.
Also Exception handling is faster in many cases than disk reads. Therefore, skipping File.Exists and just trying to read files may be better.
Tip In some situations, File.Exists is still useful. It may prevent an incorrect state in memory.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 29, 2022 (rewrite).
© 2007-2024 Sam Allen.