0

I want to search a folder by its name. But I don't know the location of the folder.

Have to get the path of that specific folder.

How Can i do it?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user1909204
  • 45
  • 1
  • 3
  • 6

3 Answers3

2

You have to specify the directory to search for the folder using Directory.GetDirectories Method (String, String, SearchOption)

string[] directories = Directory.GetDirectories(@"c:\",
                                                 "*", 
                                                 SearchOption.AllDirectories);

To get all drives from the computer, use DircotoryInfo.GetDrives and then search in all of them you can try:

DriveInfo[] allDrives = DriveInfo.GetDrives();
List<string> directoryList = new List<string>();
foreach (DriveInfo d in allDrives)
{
    directoryList.AddRange(Directory.GetDirectories(d.Name , "*", SearchOption.AllDirectories));
}
Habib
  • 219,104
  • 29
  • 407
  • 436
  • But what if its in D or E drive??? do I have to search for all of them separately? – user1909204 Jan 09 '13 at 06:58
  • 1
    @user1909204, did you check the 2nd part of the answer, You can get all the drives and then search between them – Habib Jan 09 '13 at 07:00
  • Directory.GetDirectories(d.Name , "*", SearchOption.AllDirectories) while doing this its giving error "Access to the path 'D:\System Volume Information' is denied." I checked the security setiings too they are fine.. – user1909204 Jan 09 '13 at 08:38
  • 1
    @user1909204, you have to put a try catch block, you can't access these folders, OS prevent you from doing that, Put a try-catch block and ignore the exception, See: http://stackoverflow.com/questions/172544/ignore-folders-files-when-directory-getfiles-is-denied-access – Habib Jan 09 '13 at 10:48
0

// Only get subdirectories that begin with the letter "p."

string[] dirs = Directory.GetDirectories(@"c:\", "p*");
Console.WriteLine("The number of directories starting with p is {0}.",dirs.Length);
foreach (string dir in dirs) 
{
  Console.WriteLine(dir);
}

Reference - Directory.GetDirectories Method (String, String)

If you dont know the drive then you need to search for all drives by changing the drives available on your system.

andy
  • 5,979
  • 2
  • 27
  • 49
  • What i m actually trying to do is i have to find a folder inside D:\\Sachin_RnD_Latest\\TestResults\\SummaryReport a folder named "version", the path \\TestResults\\SummaryReport is constant but not "D:\\Sachin_RnD_Latest\", now how can I get the files contained in that version folder? – user1909204 Jan 09 '13 at 07:26
  • Do you have the permissions to do it? If you don't, your program won't either. – Cullub Aug 07 '14 at 18:50
0

the only solution is using recursive search to surf all available folders and sub folders and also to jump access denied paths to have complete list of target result.