Prithiv
Prithiv

Reputation: 504

How to get the folder path from the given folder path?

I need to search the folder whether it exists or not in the given folder path. Please suggest me your ideas.

For example:

  1. I have provided the path as "E:\TestSource
  2. In that "TestSource" ,i have "Sample" folder;
  3. In that "sample" folder, i have "Details" folder
  4. Now i provide text as "Sample".
  5. 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

Answers (2)

user7351608
user7351608

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

sujith karivelil
sujith karivelil

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

Related Questions