Pregunta

I'm tring the test to see if a DirectoryInfo[] contains a directory my code is below

DirectoryInfo[] test = dir.GetDirectories();
if(test.Contains(new DirectoryInfo(dir.FullName +"\\"+ "Test_Folder")))
{
    ContainsTestFolder = true;
}

To me this should work but it does not seem to return true when it should. Any ideas to what I am doing wrong.

¿Fue útil?

Solución

Use Enumerable.Any

DirectoryInfo[] test = dir.GetDirectories();
if (test.Any(r => r.FullName.Equals(Path.Combine(dir.FullName,"Test_Folder"))))
{
   ContainsTestFolder = true;
}

The reason you are not getting the desired result is, Contains compare object reference, not its values. Also consider using Path.Combine instead of concatenating paths.

Otros consejos

You tried to compare two complex objects where all properties are not equals, prefer just comparing their FullName properties.

Prefer using predicate use FirstOrDefault and compare Directories' FullName

FirstOrDefault returns an object if found and null if not found

DirectoryInfo[] test = dir.GetDirectories();
if (test.FirstOrDefault(x => x.FullName.Equals(Path.Combine(dir.FullName,"Test_Folder"))) != null)
{
   ContainsTestFolder = true;
}

You can use also Any predicate which return a bool.

DirectoryInfo[] test = dir.GetDirectories();
if (test.Any(x => x.FullName.Equals(Path.Combine(dir.FullName,"Test_Folder"))))
{
    ContainsTestFolder = true;
}

You cannot test it this way because you're checking 2 different objects which have one property the same for equality.

Try

DirectoryInfo[] test = dir.GetDirectories();
if (test.Any(x => x.FullName.Equals(dir.FullName +"\\"+ "Test_Folder")))
{
   ContainsTestFolder = true;
}

You can also use .Contains as below:

var path = Directory.GetCurrentDirectory();
var ctf = Directory.GetDirectories(path).Contains(Path.Combine(path, "Test_Folder"));

This also avoids the need for DirectoryInfo altogether

Check your directory status ( if it contains any sub directories as )

if(test.length >0) { // Do you coding here }enter code here
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top