[英]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,但应用程序未在管理员权限下运行:
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.