file exists by file name pattern

C#.Net 2.0.Net

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJL.View Question on Stackoverflow
Solution 1 - C#monkey_pView Answer on Stackoverflow
Solution 2 - C#Claudio RediView Answer on Stackoverflow
Solution 3 - C#Mitch WheatView Answer on Stackoverflow