如何在计算机中查找目录 [英] How to find directory in computer

查看:121
本文介绍了如何在计算机中查找目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想知道是否可以仅使用Name查找Directory fullPath。例如,目录名称为Dir1。这个Dir1在PC的某个地方,它可以在C或D盘上。



我尝试过:



我试图使用FileInfo和DirectoryInfo但是对于他们我需要filePath。

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.

推荐答案

至少有一个应用程序在那里如果这就是你所需要的,那将会做到这一点 - everything.en.softonic.com



你不说为什么你需要这个 - 它是一个 - 时间的事吗?它是否真的是你想要的应用程序?



如果你真的需要在一个应用程序中使用这个功能,那么DirectoryInfo可能会很有用,但是你' ll可能需要从以下开始:



Environment.GetLogicalDrives()

返回包含逻辑驱动器名称的字符串数组当前的电脑。



Environment.GetLogicalDrives Method(System) [ ^ ]



您可能想要使用某种形式的递归,但我建议使用一种允许多线程的技术(如果需要的话)。



需要注意的是有可能存在重新分析点目录结构e创建循环引用,使您的方法永远运行 - 您可能需要一种方法来保存已搜索的目录列表,并始终在搜索之前进行检查。
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.


请参阅 Directory.GetDirectories Method(String,String)(System.IO) [ ^ ]。


正如其他人所指出的,最好的方法是通过DirectoryInfo.GetDirectories(string searchPattern,SearchOption searchOption)方法。但请确保a)手动执行递归以避免UnauthorizedAccessException,并且b)在ROM驱动器的情况下,检查IsReady是否避免设备未准备好错误。



现在,要提供示例或在特定驱动器或所有可用逻辑驱动器(不包括网络驱动器)上查找给定目录名,请参阅以下内容:



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:

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


这篇关于如何在计算机中查找目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆