2011-09-19 100 views
8

我曾与一个名为如何检查文件名包含在C#中的子

  1. myfileone
  2. myfiletwo
  3. myfilethree

文件的文件夹我如何检查文件 “myfilethree” 是当下。

我的意思是除IsFileExist()方法外,还有另一种方法,即像filename包含子字符串“three”?

+2

如果你有一个可行的解决方案(即'File.Exists'),你能解释更多关于你想要做什么,导致你需要一个替代解决方案吗? –

回答

16

字符串:

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

不区分大小写字符串:

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

区分大小写的比较:

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

获取文件名匹配通配符标准:

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

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

这工作。由于Abatischev – sreeprasad

+0

@SREEPRASADGOVINDANKUTTY很高兴帮助:) – abatishchev

+0

很好的答案,但我怎么会这样做2列表?我有一个列表,我想比较一下。 – Robula

3

如果我正确理解你的问题,你可以不喜欢

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

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

东西这两会给你的所有文件的所有名称与three在它。

0

我不熟悉IO,但也许这会工作?需要using System.Linq

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

编辑:请注意,这将返回字符串数组。

相关问题