2020年6月27日 星期六

【C#】Verify permission of specific directory

Actual verification of read permission to specific directory without opens a stream.

  1. private static bool HasPermissionToReadFiles(string path)
  2. {
  3. var readAllow = false;
  4. var readDeny = false;
  5. var firstFoundFile = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories).FirstOrDefault();
  6. if (firstFoundFile == null)
  7. {
  8. throw new Exception("There is no file in provided path.");
  9. }
  10. var accessControlList = Directory.GetAccessControl(firstFoundFile);
  11. if (accessControlList == null)
  12. return false;
  13. var accessRules = accessControlList.GetAccessRules(true, true, typeof(SecurityIdentifier));
  14. if (accessRules == null)
  15. return false;
  16.  
  17. foreach (FileSystemAccessRule rule in accessRules)
  18. {
  19. if ((FileSystemRights.Read & rule.FileSystemRights) != FileSystemRights.Read) continue;
  20.  
  21. if (rule.AccessControlType == AccessControlType.Allow)
  22. readAllow = true;
  23. else if (rule.AccessControlType == AccessControlType.Deny)
  24. readDeny = true;
  25. }
  26.  
  27. return readAllow && !readDeny;
  28. }


沒有留言:

張貼留言