开发者

How to check if filename contains substring in C#

I have a folder with files named

  1. myfileone
  2. myfiletwo
  3. myfilethree

How can I check if file "myfilethree" is present.

I mean is there another method other than IsFileExist(开发者_StackOverflow社区) method, i.e like filename contains substring "three"?


Substring:

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 comparison:

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

Get file names matching a wildcard criteria:

IEnumerable<string> files = Directory.EnumerateFiles(path, "three*.*"); // lazy file system lookup

string[] files = Directory.GetFiles(path, "three*.*"); // not lazy


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

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

or

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

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


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

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

EDIT: Note that this returns array of strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜