c# - 为什么即使 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
它在那里完美运行。关于如何解决这个问题或导致它的任何想法?
解决方案
修复!改用文档中的这段代码(但仍然不知道为什么它以前不起作用)。
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
.
推荐阅读
- python-3.x - PUT 请求 DJANGO REST 框架中的运行时错误
- python - 读取输出文件中重复但具有不同关联值的行
- c - 访问 inode 表以列出所有文件名
- python - python 3.9+ 的 nb_conda_kernels 等价物是什么?
- swift - 作为内容传递给 UIViewRepresentable 时,SwiftUI 文本动态类型不起作用
- typescript - “dom.d.ts”Window.Element(和朋友)不存在
- r - 在 R 中创建 SDMX 文件
- c# - 为什么绑定重定向后程序集加载器无法匹配 dll 修订?
- python - gcsfs 异步接口似乎不起作用(使用简单示例时出错)
- applescript - applescript:对特定消息的自动响应