2

How do I check whether a folder named xyz exist in a given path(recursively) and if it exits then get its full path so that I can copy some files from it? Will something like below work or am I missing something?

if (Directory.Exists(Path.Combine(textBox1.Text, "xyz")) { string directoryPath = Path.GetDirectoryName(textBox1.Text); } 

1 Answer 1

2

Use this:

Directory.GetDirectories(root, directoryName, SearchOption.AllDirectories); 

where root is the path to start in and directoryName is the specific name you're looking for. You can use .Any() to check if it exists and .First() to get the first.

edited after pinkfloydx33 comment

Yeah, EnumerateDirectories would be better. Sorry, I'm stuck in .net 3.5 mode at the moment :D so you'd be looking for this:

Directory.EnumerateDirectories(root, directoryName, SearchOption.AllDirectories).FirstOrDefault(); 

and checking for null.

Sign up to request clarification or add additional context in comments.

3 Comments

It depends on what you're looking for. Arrays are type-castable to IEnumerable so you can use Directory.GetDirectories(root, directoryName, SearchOption.AllDirectories).FirstOrDefault() to get null or the first item in the list. I would expect that you'd need the list though, but I suppose it depends on what you're trying to achieve.
EnumerateDirectories would be preferable- and it returns an enumerable. GetDirectories will return all results at once which means if there were thousands of matches you gets a large array the could potentially take a lot of time as well. EnumerateDirectories on the other hand will stop at the first match if you were using Any/First/FirstOrDefault and you can always call ToArray/ToList if needed. Probably not a big deal here, but this exact thing has bitten me in a production app and ever since I never use GetDirectories/GetFiles
@pinkfloydx33 Can you show it with some code, I'm getting a bit confused...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.