Reputation: 504
I need to search the folder whether it exists or not in the given folder path. Please suggest me your ideas.
For example:
- I have provided the path as "E:\TestSource
- In that "TestSource" ,i have "Sample" folder;
- In that "sample" folder, i have "Details" folder
- Now i provide text as "Sample".
- I need to search "Sample" folder.
How to get the full path of "Details" folder? Output: E:\TestSource\Sample\Details.
Thanks in Advance
Upvotes: 0
Views: 93
Reputation: 451
Use the .Net DirectoryInfo class. With this you will be able to look into sub directories dynamically. MSDN Documentation
DirectoryInfo mainDirectory = new DirectoryInfo("E:\\TestSource");
foreach(DirectoryInfo subDirectory in mainDirectory.GetDirectories())
{
Console.WriteLine(subDirectory.FullName);
//go another layer deep or write a recursive method
foreach(DirectoryInfo sub in subDirectory.GetDirectories())
{
Console.WriteLine(sub.FullName);
}
}
Upvotes: 2
Reputation: 29016
Hope that you are looking for something like :
string givenPath = @"E:\TestSource";
string searchFolder = "sample";
if (Directory.Exists(givenPath))
{
string pathToSample = Directory.EnumerateDirectories(givenPath, searchFolder, SearchOption.TopDirectoryOnly)
.FirstOrDefault(x => x != "");
}
If you want to search for sub-folders as well(let the search text be Details
) then you have to change the SearchOption
to SearchOption.AllDirectories
in this case the variable searchFolder
should be initialized with "Details"
then you will get the output as E:\TestSource\Sample\Details.
Another case to consider here is, Suppose you may have N
number of folders with name Details
in different levels of the sub-folders then FirstOrDefault
will give you the first found result, If you need all folders path means you should iterate through the result like the following instead for FirstOrDefault
foreach (string folderPath in Directory.EnumerateDirectories(givenPath, searchFolder, SearchOption.AllDirectories))
{
// iterating the list
}
Upvotes: 2