Question

I have the following code, I receive an error at "if statement" saying that FileInfo does not contain a definition "Contains"

Which is the best solution for looking if a file is in a directory?

Thanks

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
}
Was it helpful?

Solution

Remove fileList.Contains(result) and use:

if (result.Any())
{

}

.Any() is a LINQ keyword for determining whether result has any items in it or not. Kinda like doing a .Count() > 0, except quicker. With .Any(), as soon as an element is found the sequence is no longer enumerated, as the result is True.

In fact, you could remove the last five lines of your code from from file in... to the bottom, replacing it with:

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

}

OTHER TIPS

you could check the count of result

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

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) { ..... }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top