Directory.Delete不起作用。 访问被拒绝错误,但在Windows资源管理器下它没关系

我搜索了SO但却一无所获。

为什么这不起作用?

Directory.Delete(@"E:\3\{90120000-001A-0000-0000-0000000FF1CE}-C"); 

上面的行将抛出exception“访问被拒绝”。 我有管理员权限,我可以用资源管理器删除目录。

它看起来像一些禁止的角色? 但Windows资源管理器可以处理它。 如何删除名称相似的目录?

谢谢大家的意见,它帮助我快速找到解决方案。

正如Phil提到“Directory.Delete失败,如果是,无论权限如何(参见msdn.microsoft.com/en-us/library/…的底部)”

此外, 无法从文件夹中删除只读属性 Microsoft说:

您可能无法使用Windows资源管理器从文件夹中删除只读属性。 此外,当您尝试将文件保存到该文件夹​​时,某些程序可能会显示错误消息。

结论:在删除之前,始终删除所有dir,文件属性与Normal不同。 所以下面的代码解决了问题:

 System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"E:\3\{90120000-0021-0000-0000-0000000FF1CE}-C1"); if (dir.Exists) { setAttributesNormal(dir); dir.Delete(true); } . . . function setAttributesNormal(DirectoryInfo dir) { foreach (var subDir in dir.GetDirectories()) setAttributesNormal(subDir); foreach (var file in dir.GetFiles()) { file.Attributes = FileAttributes.Normal; } } 

我使用了binball的代码并添加了一行来将目录属性设置为normal。

 if (dir.Exists) { setAttributesNormal(dir); dir.Delete(true); } function setAttributesNormal(DirectoryInfo dir) { foreach (var subDir in dir.GetDirectories()) { setAttributesNormal(subDir); subDir.Attributes = FileAttributes.Normal; } foreach (var file in dir.GetFiles()) { file.Attributes = FileAttributes.Normal; } } 

根据您正在使用的目录,您可能需要管理员权限才能删除文件。 要对此进行测试,请从资源管理器中以管理员身份运行您的应用程序,看看它是否有效(右键单击.exe并选择“以管理员身份运行”)。

如果可行,您需要在应用程序执行时获得管理员权限。 您可以通过将以下内容添加到应用程序清单来执行此操作:

        

您是否尝试创建DirectoryInfo类的新实例,然后在删除之前检查存在? 代码如下所示:

  System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"E:\3\{90120000-001A-0000-0000-0000000FF1CE}-C"); if (dir.Exists) dir.Delete(true); 

此外,请validation您(运行应用程序的用户)是否可以访问该文件夹。 如果这是网络映射驱动器,则需要能够由运行该应用程序的用户删除它。

希望这可以帮助!

我有这个症状,它实际上是explorer.exe本身锁定目录。 我发现这是使用handle.exe ,但也可以使用powershell来查找锁定文件的进程:

 $lockedFile = "C:\Windows\System32\wshtcpip.dll" Get-Process | foreach{$processVar = $_; $_.Modules | foreach { if ($_.FileName -like "${lockedFile}*") { $processVar.Name + " PID:" + $processVar.id + " [" + $_.Filename + "]"}}} 

然后,您必须决定是否尝试优雅地停止该过程; 修改powershell脚本以尝试杀死锁定文件的任何进程很容易:

 $lockedFile = "C:\directory_I_want_to_delete" Get-Process | foreach{$processVar = $_; $_.Modules | foreach { if ($_.FileName -like "${lockedFile}*") { write-host $processVar.Name + " PID:" + $processVar.id + " [" + $_.Filename + "]" ; write-host "Killing process..." ; stop-process -pid $processVar.id -force }}}