How to check if file name contains substring in C #

I have a folder with files named

  • myfileone
  • myfiletwo
  • myfilethree

How to check if myfilethree file is present.

I mean, is there a different method than the IsFileExist() method, that is, the file name contains the substring "three"?

+8
c #
source share
3 answers

substrings:

 bool contains = Directory.EnumerateFiles(path).Any(f => f.Contains("three")); 

Case insensitive substring:

 bool contains = Directory.EnumerateFiles(path).Any(f => f.IndexOf("three", StringComparison.OrdinalIgnoreCase) > 0); 

Case insensitive:

 bool contains = Directory.EnumerateFiles(path).Any(f => String.Equals(f, "myfilethree", StringComparison.OrdinalIgnoreCase)); 

Get file names that match the substitution criteria:

 IEnumerable<string> files = Directory.EnumerateFiles(path, "three*.*"); // lazy file system lookup string[] files = Directory.GetFiles(path, "three*.*"); // not lazy 
+16
source share

If I understood your question correctly, you could do something like

Directory.GetFiles(directoryPath, "*three*")

or

Directory.GetFiles(directoryPath).Where(f => f.Contains("three"))

Both of them will give you all the names of all files with three in it.

+3
source share

I am not familiar with IO, but maybe this will work? Requires using System.Linq

 System.IO.Directory.GetFiles("PATH").Where(s => s.Contains("three")); 

EDIT: Note that this returns an array of strings.

0
source share

All Articles