简体   繁体   English

删除目录返回对路径的访问被拒绝

[英]Delete directory returns access to the path is denied

I have code that looks for empty directories that are older than 1 hour and deletes them 我有查找低于1小时的空目录并将其删除的代码

foreach (DirectoryInfo __dir in _directories)
{
    if (!__dir.EnumerateFiles().Any() && __dir.LastWriteTime < DateTime.Now.AddHours(-1))
    {
        Directory.Delete(__dir.FullName)
    }
}

That throws an exception saying access to the directory path is denied. 抛出一个异常,表示拒绝访问目录路径。 However I'm able to manually delete the same directory through file explorer. 但是,我可以通过文件资源管理器手动删除同一目录。
I tried what other people suggested (setting attributes to normal), but that didn't work. 我尝试了其他人的建议(将属性设置为正常),但这没有用。

I tried FileAttributes.Normal; 我试过FileAttributes.Normal; and ~FileAttributes.ReadOnly; ~FileAttributes.ReadOnly; Neither of them work. 他们都不工作。
I also tried setting access control to full control of the directory I'm trying to delete as well as it's parent directories. 我还尝试将访问控制设置为完全控制要删除的目录及其父目录。

If program posted above cannot delete the Directory but otherwise you can manually and it's a permission issue, since manually you are logged is as admin, but application is not running under administrator permission: 如果上面发布的程序无法删除目录,但是您可以手动删除目录,这是一个权限问题,因为手动登录的用户是admin,但应用程序未在管理员权限下运行:

  • For a console / UI application, Visual studio / exe is running under lesser permission, open visual studio under admin permission or run the exe as an administrator, it shall be able to able to achieve the purpose 对于控制台/ UI应用程序,Visual Studio / exe在较小的权限下运行,在admin权限下打开Visual Studio或以管理员身份运行exe,则应能够达到目的。
  • For ASP.Net web application, it would be running under the context of a IIS user, check out users and groups, provide permission to that user over the directory. 对于ASP.Net Web应用程序,它将在IIS用户的上下文中运行,签出用户和组,并在目录上向该用户提供权限。

If FileAttributes.Normal; 如果FileAttributes.Normal; doesn't do the trick (which it should) try setting the Attributes to ReadOnly: 不能做到这一点(应该这样做)尝试将Attributes设置为ReadOnly:

foreach (DirectoryInfo __dir in _directories)
{
    if (!__dir.EnumerateFiles().Any() && __dir.LastWriteTime < DateTime.Now.AddHours(-1))
    {
       __dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
       __dir.Delete();
    }
}

Also note this uses __dir to delete itself instead of the Directory.Delete(__dir.FullName) , it shouldn't make a difference, just shorthand. 还要注意,它使用__dir而不是Directory.Delete(__dir.FullName)来删除自身,它不应该有所作为,只是简写。

连同其他建议一起,请确保您要删除的目录(例如:读取或写入目录的文件)中的程序均未在“做某事” ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM