简体   繁体   中英

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

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; and ~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:

  • 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
  • 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.

If FileAttributes.Normal; doesn't do the trick (which it should) try setting the Attributes to 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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