[英]C# folder permissions
我需要拥有该文件夹及其子文件夹的所有权才能删除它。 手动处理对我来说很好:
但是我有大约一百个这样的文件夹( 原因 ),所以我想以编程方式删除它们。
我的代码获得了文件夹的所有权,而不是子文件夹的所有权。
var identity = WindowsIdentity.GetCurrent().User;
var dirInfo = new DirectoryInfo(dirPath);
var dirSecurity = dirInfo.GetAccessControl();
dirSecurity.SetOwner(identity);
var fullControlRule = new FileSystemAccessRule(identity,
FileSystemRights.FullControl,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow);
dirSecurity.AddAccessRule(fullControlRule);
dirInfo.SetAccessControl(dirSecurity);
之后尝试删除文件夹时,出现System.UnauthorizedAccessException:拒绝访问路径'C:\\ a4f31eae62bde1cb4d49834897 \\ Sandbox'。
任何帮助将非常感激! 谢谢。
对我有用的最终解决方案是使用命令行(PowerShell)的接管服务 。 虽然我仍然对C#解决方案感到迷惑...
感谢用户后来删除了他的建议。
最终的PowerShell代码清除提到的文件夹:
$dirNames = Get-ChildItem "C:\" | Select-String -Pattern "[a-f0-9]{18,30}"
foreach ($dirName in $dirNames) {
TakeOver("C:\$dirName")
}
function TakeOver($dirPath) {
takeown /f $dirPath /r /d Y
#icacls $dirPath /reset /T
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.