How to find out if an Array FileInfo [] file contains a file

I have the following code, I get an error in the expression "if" saying that FileInfo does not contain the definition of "Contains"

What is the best solution to find a file in a directory?

thank

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
}
+5
source share
3 answers

Remove fileList.Contains(result)and use:

if (result.Any())
{

}

.Any()is the LINQ keyword to determine if a result has any elements in it or not. As if to do .Count() > 0, except faster . C .Any(), as soon as an element is found, the sequence will no longer be listed, as the result True.

from file in... , :

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

}
+13

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

How about this, the code below will give you a list of files (full name as a string); the reason why returning as a list is because your subdirectories may have the same file name as "test.txt".

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

if you are sure that the test.txt file will be in only one of the directories, you can use:

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

All Articles