Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
1.67/5 (3 votes)
See more:
So I want to know if it is possible to find Directory fullPath only with Name. For Example Directory name is Dir1. And this Dir1 is somewhere in PC, it can be on disk C or D.

What I have tried:

I tried to use FileInfo and DirectoryInfo but for them I need filePath.
Posted
Updated 14-Jul-16 3:15am
Comments
ZurdoDev 9-Jul-16 13:47pm    
Yes, just use DirectoryInfo. Where are you stuck?
dave_bulac 9-Jul-16 14:39pm    
See my Comment below

There is at least one application out there that will do this if that's all you need -- everything.en.softonic.com

You don't say why you need this -- is it a one-time thing? Is it really something you want in an application?

If you really need to have this feature in an application, then DirectoryInfo is probably going to be usefull, but you'll probably need to start with:

Environment.GetLogicalDrives()
Returns an array of string containing the names of the logical drives on the current computer.

Environment.GetLogicalDrives Method (System)[^]

And you will probably want to use some form of recursion, but I suggest using a technique that allows for multi-threading (if it's needed).

And something to watch out for is the possibility that there are reparse points in the directory structure that create circular references that would cause your method to run forever -- you will likely need a way to keep a list of the directories you have already searched, and always check before searching.
 
Share this answer
 
Comments
BillWoodruff 9-Jul-16 14:22pm    
+5
dave_bulac 9-Jul-16 14:27pm    
I am using this code:
DirectoryInfo dr = new DirectoryInfo("CV");
Console.WriteLine(dr.FullName);

but in this it gives such a result:
c:\users\dave\documents\visual studio 2015\Projects\Exp\Exp\bin\Debug\CV

In case "CV" is located in "Local Disk D" and not in that Directory.
Than I have tried it for another Directory, that is located on Desktop, but it gives similar Result.
PIEBALDconsult 9-Jul-16 15:03pm    
The "working directory" of your application is the directory that contains the executable.
Try "\\CV", but you will need to search to find what you are looking for.
dave_bulac 9-Jul-16 15:36pm    
I am looking for a Directory "CV", that is located on Local Disk D.
PIEBALDconsult 9-Jul-16 15:45pm    
You will need to start at the root and search the directory tree.
You can search depth-first or breadth-first, but you must search; no one is going to do it for you.
As everyone else pointed out, the best means is via the DirectoryInfo.GetDirectories(string searchPattern, SearchOption searchOption) method. But make sure to a) manually perform the recursion in order to avoid an UnauthorizedAccessException, and b)in the case of ROM drives, check if IsReady to avoid a "Device is not ready" error.

Now, to provide an example or finding a given directory name on a specific drive, or on all available logical drives (excluding network drives), please see the following:

C#
static void Main(string[] args)
{
   DirectoryInfo selectedDir;

   // Find a directory called "Exported" on any available logical drive.
   // If you need to find the directory on a spicific logical drive, provide the DriveInfo for the drive to search.
   selectedDir = FindDirectory("Exported");
   if (selectedDir == null)
   {
      Console.WriteLine("No directory was found matching the provided name.");
   }
   else
   {
      Console.WriteLine("The folloiwng directory path was selected:");
      Console.WriteLine(selectedDir.FullName);
   }
            
   Console.ReadLine();
}

static DirectoryInfo FindDirectory(string dirNameToFind, DriveInfo driveToSearch = null)
{
   // Prevent null strings or searching for invalid directory names (contains invalid charaters).
   if ((String.IsNullOrEmpty(dirNameToFind)) || (!IsValidDirectoryName(dirNameToFind))) { return null; }

   List<directoryinfo> possibleDirs = new List<directoryinfo>();

   if (driveToSearch == null)
   {
      // No drive was specified, so search all drives.
      foreach (DriveInfo availableDrive in DriveInfo.GetDrives())
      {
         // Only check non-network drives and drives with removable media that are ready (disk installed).
         if ((availableDrive.DriveType != DriveType.Network) && (availableDrive.IsReady))
         {
            DirectoryInfo driveRootDir = new DirectoryInfo(availableDrive.Name);
            GetDirectories(possibleDirs, driveRootDir, dirNameToFind);
         }
      }
   }
   else
   {
      // A drive was provided, so only search that drive.
      DirectoryInfo driveRootDir = new DirectoryInfo(driveToSearch.Name);
      GetDirectories(possibleDirs, driveRootDir, dirNameToFind);
   }
            
   if (possibleDirs.Count() == 0) { return null; }  // No dir matches, so return null.
   if (possibleDirs.Count() ==1) { return possibleDirs[0]; } // Only one dir matched, so return that dir.


   // More than one directory exsits matching the provided name. So ask the user to which directory they want.
   Console.WriteLine("Multiple directories were found matching the provided name.");
   Console.WriteLine("Please indicate which directory to use.");
   Console.WriteLine();

   for (int i = 1; i <= possibleDirs.Count(); i++) { Console.WriteLine(i.ToString() + ": " + possibleDirs[i - 1].FullName); }

   Console.WriteLine();

   bool vaidInput = false;
   int selectedItemNo = -1;
   do
   {
      Console.WriteLine("Enter corrisponding number and press enter.");
      string userInput = Console.ReadLine();

      if (String.IsNullOrEmpty(userInput)) { continue; }  // Handle blank entries.

      vaidInput = int.TryParse(userInput, out selectedItemNo);
   }
   while ((!vaidInput) && (Enumerable.Range(1, possibleDirs.Count()).Contains(selectedItemNo)));

   return possibleDirs[selectedItemNo - 1];
}

static bool IsValidDirectoryName(string directoryName)
{
   foreach (char c in Path.GetInvalidPathChars())
   {
      if (directoryName.Contains(c)) { return false; }
   }
   return true;
}

static void GetDirectories(List<directoryinfo> dirList, DirectoryInfo rootDir, string dirNameToFind = null)
{
   // Perform manual recurrsion to prevent "UnauthorizedAccessException" errors.
   try
   {
      foreach (DirectoryInfo subDir in rootDir.GetDirectories("*", SearchOption.TopDirectoryOnly))
      {
         if ((String.IsNullOrEmpty(dirNameToFind)) || (subDir.Name == dirNameToFind)) { dirList.Add(subDir); }
         GetDirectories(dirList, subDir, dirNameToFind);
      }
   }
   catch (UnauthorizedAccessException) {  }    // Do nothing.
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900