5

我有以下代码,我在“if 语句”中收到一个错误,指出 FileInfo 不包含定义“包含”

哪个是查找文件是否在目录中的最佳解决方案?

谢谢

string filePath = @"C:\Users\";
DirectoryInfo folderRoot = new DirectoryInfo(filePath);
FileInfo[] fileList = folderRoot.GetFiles();

IEnumerable<FileInfo> result = from file in fileList where file.Name == "test.txt" select file;
if (fileList.Contains(result))
{
      //dosomething
}
4

3 回答 3

17

删除fileList.Contains(result)并使用:

if (result.Any())
{

}

.Any()是一个 LINQ 关键字,用于确定 result 中是否有任何项目。有点像做一个.Count() > 0,除了更快。使用.Any(),只要找到一个元素,就不再枚举序列,结果是True

实际上,您可以从底部删除最后五行代码from file in...,将其替换为:

if (fileList.Any(x => x.Name == "test.txt"))
{

}
于 2012-06-13T14:42:16.797 回答
3

你可以检查结果的计数

 if (result.Count() > 0)
 {
    //dosomething
 }
于 2012-06-13T14:44:59.357 回答
0

How about this, code below will give you a list of files (fullname as a string); the reason why return as a list is because your sub directories may have the same file name as 'test.txt'.

var list = Directory.EnumerateFiles(@"c:\temp\", "test.txt",
           SearchOption.AllDirectories);

if you are very sure 'test.txt' file will only in one of the directory, you can use:

string fullname = Directory.EnumerateFiles(@"c:\temp\", "test.txt",
                  SearchOption.AllDirectories).FirstOrDefault();
if (fullname != null) { ..... }
于 2013-03-22T02:51:12.350 回答