88

I am using:

File.Exists(filepath) 

I would like to swap 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?

0

4 Answers 4

135

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 } 
Sign up to request clarification or add additional context in comments.

Comments

81

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.

3 Comments

Your version of code make same thing, but hidden. No way to get all files matching pattern just from nothing.
@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
If you are stuck in 3.5 you can use bool exist = Directory.GetFiles(path, "*_peach.xml").Any();
6

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

Also see Stack Overflow questions:

And many others...

Comments

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: File globbing in .NET

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.