Check if a File Exists in C# or VB.Net

File.Exists Method

File.Exists Method c#

The File Class provides static methods for the creation, copying, deletion, moving, and opening of a single file. Also it provides a method File.Exists() for checking a File exist or not.


The File.Exists method returns a Boolean value.

File.Exists method returns a Boolean value c#

It will return true if the caller has the required permissions and path contains the name of an existing file, otherwise it will return false. Also passing an invalid path will return returns false

It is easy to check with the conditional operator (?).

File.Exists("d:\\product1.xml") ? "File exists" : "File does not exist"

Search File using wild card

You can use wild card characters to check a file exists in a folder.

How to check if a file exists in a folder?

Source Code | C#
string[] files = Directory.GetFiles("D:\\", "*.doc", SearchOption.AllDirectories); foreach (string s in files) { MessageBox.Show(s); }

Source Code | Vb.Net
Dim files As String() = Directory.GetFiles("D:\", "*.doc", SearchOption.AllDirectories) For Each s As String In files MessageBox.Show(s) Next

You can use searchoption enumeration to specifies whether to look in the current directory, or the current directory and all subdirectories.


SearchOption.AllDirectories includes the current directory and all its subdirectories in a search operation.


SearchOption.TopDirectoryOnly includes only the current directory in a search operation.

.Net Framework 4

If you are using Microsoft .Net Framework 4 or above you can use Directory.EnumerateFiles.

bool fileExist = Directory.EnumerateFiles(path, "*.doc").Any();
File exist in Network Path c#

This method will be more efficient than using Directory.GetFiles because you can avoid to iterate trough the entire file list.

Check File exist in Network Path

FileInfo sFile = new FileInfo(@"\\server\share\file.xml"); bool fileExist = sFile.Exists;

NEXT.....Decimal vs Double vs Float