如何知道数组文件信息[]是否包含文件

本文关键字:文件 是否 包含 信息 何知道 数组 | 更新日期: 2023-09-27 18:37:07

我有以下代码,我在"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
}

如何知道数组文件信息[]是否包含文件

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

if (result.Any())
{
}

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

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

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

你可以检查结果的计数

 if (result.Count() > 0)
 {
    //dosomething
 }

怎么样,下面的代码会给你一个文件列表(全名为字符串); 返回为列表的原因是因为你的子目录可能与'test.txt具有相同的文件名。

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

如果你非常确定"test.txt"文件只会在其中一个目录中,你可以使用:

string fullname = Directory.EnumerateFiles(@"c:'temp'", "test.txt",
                  SearchOption.AllDirectories).FirstOrDefault();
if (fullname != null) { ..... }