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

狂风中的少年 提交于 2020-01-03 05:14:06

问题


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?


回答1:


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



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/14229203/search-for-a-folder-by-its-name-in-c-sharp-without-specifying-the-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!