83

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?

John Saunders
  • 159,224
  • 26
  • 237
  • 393
JL.
  • 75,548
  • 121
  • 304
  • 451

3 Answers3

128

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
}
VisualMelon
  • 661
  • 12
  • 23
monkey_p
  • 2,799
  • 2
  • 17
  • 16
76

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.

Claudio Redi
  • 65,896
  • 14
  • 126
  • 152
  • Your version of code make same thing, but hidden. No way to get all files matching pattern just from nothing. – Kostadin Feb 17 '17 at 08:22
  • 4
    @Kostadin: missed to answer this before... he doesn't want to get all files matching a pattern, he wants to know if there is ANY – Claudio Redi Sep 22 '17 at 02:19
  • If you are stuck in 3.5 you can use bool exist = Directory.GetFiles(path, "*_peach.xml").Any(); – Joe Johnston May 21 '20 at 17:35
6

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...

Community
  • 1
  • 1
Mitch Wheat
  • 288,400
  • 42
  • 452
  • 532