首页 > 解决方案 > 为什么即使 Directory.Exists 返回 true,它也会抛出 DirectoryNotFoundException?

问题描述

所以我正在制作一个非常小的控制台应用程序来组织一些目录,因为我想至少知道一些关于如何在 C# 上处理文件和目录的基本知识,为此我使用了Directory.Move,像这样:

Environment.CurrentDirectory = "/";
try
{
 string subDirectoryPath = Path.GetFullPath(subDirectoryName);
 string newCompletePath = Path.GetFullPath(newPath);
 if (Directory.Exists(subDirectoryPath) && !Directory.Exists(newCompletePath))
 {
  Directory.Move(subDirectoryPath, Path.GetFullPath(newPath));
  SuccessMessage("{0}: -> {1}", subDirectoryName, newPath);
 }
 ErrorMessage($"The path `{subDirectoryPath}` doesn't exists!");
}
catch (DirectoryNotFoundException ex)
{
 ErrorMessage(ex.Message);
 ErrorMessage(ex.StackTrace);
 Errors.Add($"ERROR ON: {subDirectoryName}");
}

奇怪的事情发生在它到达 deif语句时,它返回 true 但是当它到达Directory.Move函数时它抛出一个DirectoryNotFoundException. 该变量subDirectoryName是通过 获得的字符串之一Directory.GetDirectories。我什至尝试过DirectoryInfo这样使用:

Environment.CurrentDirectory = "/";
try
{
 DirectoryInfo directoryInfo = new DirectoryInfo(subDirectoryName);
 directoryInfo.MoveTo(newPath);
}
catch (DirectoryNotFoundException ex)
{
 ErrorMessage(ex.Message);
 ErrorMessage(ex.StackTrace);
 Errors.Add($"ERROR ON: {subDirectoryName}");
}

但是,仍然没有成功,并且抛出的异常保持不变。

我在 Mac 上,使用 Visual Studio for Mac,没有任何异步运行会影响该路径,Finder 上的 GoTo 快捷方式与subDirectoryPath.

我怀疑它与目录的名称有关,因为它们可能有一些奇怪的字符,例如这是其中之一:( /Users/elrohir/Downloads/Comics/[Gokusaishiki (Aya Shachou)] Chikokuma Renko 2 ~Fukushuu no Chikokusha~奇怪的字符是〜)。我尝试使用更简单的名称,例如:/Users/elrohir/Downloads/Comics/Comic Name 1它在那里完美运行。关于如何解决这个问题或导致它的任何想法?

标签: c#file-iodirectoryfilesystemsconsole-application

解决方案


修复!改用文档中的这段代码(但仍然不知道为什么它以前不起作用)。

Environment.CurrentDirectory = "/";
 try
 {
   DirectoryInfo directoryInfo = new DirectoryInfo(subDirectoryName);

   if (!Directory.Exists(newPath))
   {
     Directory.CreateDirectory(newPath);
   }

   foreach(FileInfo image in directoryInfo.GetFiles())
   {
     image.CopyTo(Path.Combine(newPath, image.Name), true);
     Console.ForegroundColor = ConsoleColor.DarkGray;
     Console.WriteLine(@"Copying {0}\{1}", newPath, image.Name);
     Console.ForegroundColor = ConsoleColor.White;
   }
     SuccessMessage("{0}: -> {1}", subDirectoryName, newPath);
 }
 catch (DirectoryNotFoundException ex)
 {
   ErrorMessage(ex.Message);
   ErrorMessage(ex.StackTrace);
   Errors.Add($"ERROR ON: {subDirectoryName}");
 }

现在里面的所有图像/文件都subDirectoryName被复制到newPath.


推荐阅读