file exists by file name pattern

I am using:

File.Exists(filepath)

What I would like to do is swop this out for a pattern, because the first part of the filename changes.

For example: the file could be

01_peach.xml
02_peach.xml
03_peach.xml

How can I check if the file exists based on some kind of search pattern?


Solution 1:

You can do a directory list with a pattern to check for files

string[] files = System.IO.Directory.GetFiles(path, "*_peach.xml", System.IO.SearchOption.TopDirectoryOnly);
if (files.Length > 0)
{
    //file exist
}

Solution 2:

If you're using .net framework 4 or above you could use Directory.EnumerateFiles

bool exist = Directory.EnumerateFiles(path, "*_peach.xml").Any();

This could be more efficient than using Directory.GetFiles since you avoid iterating trough the entire file list.

Solution 3:

Get a list of all matching files using System.IO.DirectoryInfo.GetFiles()

Also see SO Questions:

Is there a wildcard expansion option for .net apps?

How do I check if a filename matches a wildcard pattern

and many others...