【发布时间】:2012-12-13 07:52:49
【问题描述】:
Windows 7 x64 SP1 .NET 框架 3.5 SP1
我编写了简单的代码,但它会随着时间的推移而起作用,异常发生在每一秒通过。 ...即:它适用于偶数开始:2、4、6、8 等,但我对奇数开始有例外:1、3、5、7、9 等
// localMenuDirName is 'GPSM\AdminCAD'.
DirectoryInfo menuDir = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.Programs), localMenuDirName));
if (menuDir.Exists) {
FileInfo[] files = menuDir.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo file in files) {
file.IsReadOnly = false;
}
sb.AppendLine(String.Format("We begin deleting the '{0}' directory", menuDir.FullName));
Directory.Delete(menuDir.FullName, true); // Get Exception here
// menuDir.Delete(true); // here I get same exception.
输出文本:
我们开始删除 'C:\Users\andrey.bushman\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\GPSM\AdminCAD' 目录
例外:目录不为空。
但目录是空的(所有文件都已删除)。我打开资源管理器看看。
下一个代码总是可以正常工作:
// localMenuDirName is 'GPSM\AdminCAD'.
DirectoryInfo menuDir = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.Programs), localMenuDirName));
if (menuDir.Exists) {
FileInfo[] files = menuDir.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo file in files) {
file.IsReadOnly = false;
}
sb.AppendLine(String.Format("We begin deleting the '{0}' directory", menuDir.FullName));
try {
Directory.Delete(menuDir.FullName, true);
}
catch {
// Try again... Now it works without exception!
Directory.Delete(menuDir.FullName, true);
}
sb.AppendLine("Operation was executed successfully.");
为什么会这样?
【问题讨论】:
-
您是否在要删除的目录中打开了当前目录的命令提示符?
-
也许您在 Windows 资源管理器中打开了该目录?然后就删不掉了,根据文档:
In some cases, if you have the specified directory open in File Explorer, the Delete method may not be able to delete it.msdn.microsoft.com/en-us/library/62t64db3.aspx -
@leppie 不,我从其他目录运行我的 exe,工作目录也是其他目录。
-
@dognose 不,我在出现异常后打开目录。
标签: c# .net windows exception directory