简体   繁体   中英

Search for a folder by its name in c# without specifying the path

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?

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

// 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.

唯一的解决方案是使用递归搜索来浏览所有可用文件夹和子文件夹,并跳过访问被拒绝的路径以获取目标结果的完整列表。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM