C#CreateDirectory表现奇怪-不创建目录 [英] C# CreateDirectory behaving strange - Not creating directory
问题描述
我正在删除目录(如果存在),然后重新创建该目录.
I am deleting a directory if it exists, and re-creating that directory.
我的代码是这样的:
if (Directory.Exists(destFolder))
{
Directory.Delete(destFolder, true);
DirectoryInfo dirInfo = Directory.CreateDirectory(destFolder);
}
else
{
Directory.CreateDirectory(destFolder);
}
我面临的问题是:如果该目录已包含文件并且该目录当前已在Windows资源管理器窗口之一中打开(即使在任何应用程序中均未打开文件),则:
The problem I am facing is: if the directory already contains files AND that directory is currently open in one of the Windows explorer windows (even though no file is open in any application), then:
- Directory.Delete删除目录,资源管理器窗口自动导航到父文件夹.
- CreateDirectory不会引发任何错误,但它返回的DirectoryInfo包含Exists为false.
由于此,稍后在我的程序中尝试在该目录中创建文件时,出现错误:找不到路径的一部分"
Due to this, later in my program when I am trying to create files in that directory, I get the error: "Could not find a part of the path"
为什么会这样?解决方法是什么?
Why is this behaviour and what is the solution?
谢谢.
有时DirectoryInfo.Exists返回true,但是目录实际上在Explorer中不存在!
EDIT 1: Sometimes DirectoryInfo.Exists returns true, but the directory does not actually exist in Explorer!
推荐答案
由于您要求的解决方案类似于不使用Thread.Sleep的vivek nuna:
Since you asked for a solution akin to vivek nuna's that doesn't use Thread.Sleep:
您还可以使用FileSystemWatcher来监视目录的删除.通常情况下,这应该比Thread.Sleep快.
You could also use a FileSystemWatcher to watch for the deletion of the directory. This should in the normal case be faster than a Thread.Sleep.
但是,如果您采用这种方式,还请设置一个计时器,并检查目录是否消失而不被告知.当托管驱动器的系统不支持通知时,FileSystemWatcher静默失败.
However, if you take this route also set a timer and check if the directory vanished without you being told. FileSystemWatcher fails silently when the system hosting the drive does not support the notifications.
这篇关于C#CreateDirectory表现奇怪-不创建目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!