86

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
  • 160,644
  • 26
  • 247
  • 397
JL.
  • 78,954
  • 126
  • 311
  • 459

4 Answers4

132

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
  • 662
  • 12
  • 23
monkey_p
  • 2,849
  • 2
  • 19
  • 16
79

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
  • 67,454
  • 15
  • 130
  • 155
  • 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
  • 295,962
  • 43
  • 465
  • 541
0

For more advanced searching against a specific pattern, it might be worth using File Globbing which allows you to use search patterns like you would in a .gitignore file.

See here: https://learn.microsoft.com/en-us/dotnet/core/extensions/file-globbing

This allows you to add both inclusions & exclusions to your search.

Please see below the example code snippet from the Microsoft Source above:

Matcher matcher = new Matcher();
matcher.AddIncludePatterns(new[] { "*_peach.xml" });

IEnumerable<string> matchingFiles = matcher.GetResultsInFullPath(filepath);
Ryan Gaudion
  • 695
  • 1
  • 8
  • 22