Sam Stephenson
Sam Stephenson

Reputation: 5190

If DirectoryInfo contain a Directory

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.

Upvotes: 2

Views: 3594

Answers (5)

trebor74
trebor74

Reputation: 133

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

Upvotes: 2

user2035329
user2035329

Reputation: 11

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

if(test.length >0) { // Do you coding here }enter code here

Upvotes: 1

Habib
Habib

Reputation: 223392

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.

Upvotes: 4

Aelios
Aelios

Reputation: 12147

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;
}

Upvotes: 3

Ivan Ferić
Ivan Ferić

Reputation: 4763

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;
}

Upvotes: 2

Related Questions